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

huangapple go评论115阅读模式
英文:

How to run external Python script in Golang?

问题

我想运行一个外部的Python脚本,它需要4个参数。如果我想在cmd中运行Python脚本,命令应该是这样的:python Required\Python\screenshot.py-master\screenshot.py --nojs -thumb http://google.com/ Required\Images\Screenshots\google.jpg
所以,我想从Go语言中运行这个命令。我应该如何实现呢?
谢谢。

英文:

I would like to run an external Python script that gets 4 arguments. If I would like to run the Python script in cmd it would look like this: python Required\Python\screenshot.py-master\screenshot.py --nojs -thumb http://google.com/ Required\Images\Screenshots\google.jpg
So, I would like to run this command from Go.
How could I implement this?
Thanks.

答案1

得分: 2

如果文档中的示例不够有帮助,也许这个例子能让你更容易理解。

test.go:

  1. package main
  2. import (
  3. "log"
  4. "os"
  5. "os/exec"
  6. )
  7. func main() {
  8. log.Println(os.Args)
  9. if len(os.Args) == 1 {
  10. return
  11. }
  12. cmd := exec.Command(os.Args[1], os.Args[2:]...)
  13. cmd.Stdout = os.Stdout
  14. cmd.Stderr = os.Stderr
  15. log.Println(cmd.Run())
  16. }

test.py:

  1. import sys
  2. print sys.argv

用法:

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

If examples from doc are not helpful, maybe this will make it easier for you.

test.go:

  1. package main
  2. import (
  3. &quot;log&quot;
  4. &quot;os&quot;
  5. &quot;os/exec&quot;
  6. )
  7. func main() {
  8. log.Println(os.Args)
  9. if len(os.Args) == 1 {
  10. return
  11. }
  12. cmd := exec.Command(os.Args[1], os.Args[2:]...)
  13. cmd.Stdout = os.Stdout
  14. cmd.Stderr = os.Stderr
  15. log.Println(cmd.Run())
  16. }

test.py:

  1. import sys
  2. print sys.argv

usage:

  1. $ go run test.go python test.py 1 two 3 four
  2. 2016/02/20 21:45:42 [/tmp/go-build772613382/command-line-arguments/_obj/exe/test python test.py 1 two 3 four]
  3. [&#39;test.py&#39;, &#39;1&#39;, &#39;two&#39;, &#39;3&#39;, &#39;four&#39;]
  4. 2016/02/20 21:45:42 &lt;nil&gt;

huangapple
  • 本文由 发表于 2016年2月21日 03:46:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/35528180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定