如何在Golang中运行外部Python脚本?

时间:2016-02-20 19:46:41

标签: python go cmd exec external

我想运行一个获得4个参数的外部Python脚本。如果我想在cmd中运行Python脚本,它将如下所示:python必需\ Python \ screenshot.py-master \ screenshot.py --nojs -thumb http://google.com/必需\ Images \ Screenshots \ google.jpg 所以,我想从Go运行这个命令。 我怎么能实现这个? 感谢。

1 个答案:

答案 0 :(得分:2)

如果doc中的示例没有帮助,也许这会让您更轻松。

test.go:

package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {
    log.Println(os.Args)
    if len(os.Args) == 1 {
        return
    }
    cmd := exec.Command(os.Args[1], os.Args[2:]...)
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    log.Println(cmd.Run())
}

test.py:

import sys
print sys.argv

用法:

$ go run test.go python test.py 1 two 3 four
2016/02/20 21:45:42 [/tmp/go-build772613382/command-line-arguments/_obj/exe/test python test.py 1 two 3 four]
['test.py', '1', 'two', '3', 'four']
2016/02/20 21:45:42 <nil>
相关问题