golang执行多个linux命令,在同一shell golang中运行多个Exec命令
我在弄清楚如何使用os / exec包运行多个命令时遇到了麻烦。我已经摸索了网络和stackoverflow,还没有找到任何适合我的案例。这是我的资料来源:package mainimport (_ "bufio"_ "bytes"_ "errors""fmt""log""os""os/exec""path/filepath")func main() {ffmpegFolderName := "f
我在弄清楚如何使用os / exec包运行多个命令时遇到了麻烦。我已经摸索了网络和stackoverflow,还没有找到任何适合我的案例。这是我的资料来源:
package main
import (
_ "bufio"
_ "bytes"
_ "errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
)
func main() {
ffmpegFolderName := "ffmpeg-2.8.4"
path, err := filepath.Abs("")
if err != nil {
fmt.Println("Error locating absulte file paths")
os.Exit(1)
}
folderPath := filepath.Join(path, ffmpegFolderName)
_, err2 := folderExists(folderPath)
if err2 != nil {
fmt.Println("The folder: %s either does not exist or is not in the same directory as make.go", folderPath)
os.Exit(1)
}
cd := exec.Command("cd", folderPath)
config := exec.Command("./configure", "--disable-yasm")
build := exec.Command("make")
cd_err := cd.Start()
if cd_err != nil {
log.Fatal(cd_err)
}
log.Printf("Waiting for command to finish...")
cd_err = cd.Wait()
log.Printf("Command finished with error: %v", cd_err)
start_err := config.Start()
if start_err != nil {
log.Fatal(start_err)
}
log.Printf("Waiting for command to finish...")
start_err = config.Wait()
log.Printf("Command finished with error: %v", start_err)
build_err := build.Start()
if build_err != nil {
log.Fatal(build_err)
}
log.Printf("Waiting for command to finish...")
build_err = build.Wait()
log.Printf("Command finished with error: %v", build_err)
}
func folderExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
我想要命令,就像从终端一样。 cd path; ./configure; make
因此,我需要依次运行每个命令,并等待最后一个命令完成后再继续。在当前版本的代码中,当前./configure: no such file or
directory假设是因为执行cd path并在新的shell中执行了./configure,而不是与上一个命令位于同一目录中。有任何想法吗?
更新 我通过更改工作目录然后执行./configure和make命令解决了该问题
err = os.Chdir(folderPath)
if err != nil {
fmt.Println("File Path Could not be changed")
os.Exit(1)
}
现在我还是很好奇,是否有办法在同一个外壳中执行命令。
更多推荐
所有评论(0)