我想創建一個包裝程序,可以包裝用戶提供的任何 shell 命令,例如:./wrapper "cmd1 && cmd2"在 Python 中,我可以調用os.system("cmd1 && cmd2"). 但是 Golangexec.Command需要一個命令和參數列表。Golang 有沒有辦法像 Python 一樣進行歸檔os.system()?
1 回答

喵喔喔
TA貢獻1735條經驗 獲得超5個贊
操作系統/執行 https://pkg.go.dev/os/exec
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("/usr/bin/bash", "-c", os.Args[1])
output, err := cmd.CombinedOutput()
if err != nil {
panic(err)
}
fmt.Println(string(output))
}
$ go run main.go "ls -alh && pwd"
total 4.0K
drwxr-xr-x 2 xxxx xxxx 120 Nov 14 11:12 .
drwxrwxrwt 17 root root 420 Nov 14 11:42 ..
-rw-r--r-- 1 xxxx xxxx 217 Nov 14 11:42 main.go
/tmp/stk
- 1 回答
- 0 關注
- 195 瀏覽
添加回答
舉報
0/150
提交
取消