Go提供的os/exec包可以執行外部程序,比如調用系統命令等。
最簡單的代碼,調用pwd命令顯示程序當前所在目錄:
package main import ( "fmt" "os/exec" ) func main() { pwdCmd := exec.Command("pwd") pwdOutput, _ := pwdCmd.Output() fmt.Println(string(pwdOutput)) }
執行后會輸出當前程序所在的目錄。
如果要執行復雜參數的命令,可以這樣:
exec.Command("bash", "-c", "ls -la")
或者這樣:
exec.Command("ls", "-la")
或者這樣:
pwdCmd := exec.Command("ls", "-l", "-a")