duanbarong4617
2014-11-19 16:09 阅读 66
已采纳

转到:运行外部Python脚本

I have tried following the Go Docs in order to call a python script which just outputs "Hello" from GO, but have failed until now.

exec.Command("script.py")

or I've also tried calling a shell script which simply calls the python script, but also failed:

exec.Command("job.sh")

Any ideas how would I achieve this?

EDIT

I solved following the suggestion in the comments and adding the full path to exec.Command().

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongnachuang6635 dongnachuang6635 2014-11-19 16:12

    Did you try adding Run() or Output(), as in:

    exec.Command("script.py").Run()
    exec.Command("job.sh").Run()
    

    You can see it used in "How to execute a simple Windows DOS command in Golang?" (for Windows, but the same idea applies for Unix)

    c := exec.Command("job.sh")
    
    if err := c.Run(); err != nil { 
        fmt.Println("Error: ", err)
    }   
    

    Or, with Output() as in "Exec a shell command in Go":

    cmd := exec.Command("job.sh")
    out, err := cmd.Output()
    
    if err != nil {
        println(err.Error())
        return
    }
    
    fmt.Println(string(out))
    
    点赞 评论 复制链接分享
  • dpb_4431 dpb_4431 2016-06-17 07:17

    First of all do not forget to make your python script executable (permissions and #!/usr/local/bin/python at the beginning).

    After this you can just run something similar to this (notice that it will report you errors and standard output).

    package main
    
    import (
        "log"
        "os"
        "os/exec"
    )
    
    func main() {
        cmd := exec.Command("script.py")
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
        log.Println(cmd.Run())
    }
    
    点赞 评论 复制链接分享

相关推荐