简体   繁体   English

从Go运行Python程序

[英]Running a Python program from Go

I have written some code in Python that uses some libraries that are not in Go. 我已经用Python编写了一些代码,这些代码使用了Go中没有的一些库。 I have a web server that I have written in Go and I would like to be able to call a Python program from my Go program and then use the output of the Python program as input in my Go program. 我有一个用Go编写的Web服务器,我希望能够从Go程序中调用Python程序,然后将Python程序的输出用作Go程序中的输入。 Is there anyway to do this? 反正有这样做吗?

It's actually relatively easy. 实际上,这相对容易。 All you need to do is use the os/exec library. 您需要做的就是使用os/exec库。 Here is an example below. 这是下面的例子。

Go Code: 验证码:

package main

import (
   "fmt"
   "os/exec"
)

func main() {
    cmd := exec.Command("python",  "python.py", "foo", "bar")
    fmt.Println(cmd.Args)
    out, err := cmd.CombinedOutput()
    if err != nil { fmt.Println(err); }
    fmt.Println(string(out))
}

Python Code: Python代码:

import sys

for i in range(len(sys.argv)):
   print str(i) + ": " + sys.argv[i]

Output From Go Code: Go代码输出:

[python python.py foo bar]
0: python.py
1: foo
2: bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM