Golang相当于在Python中创建子流程

时间:2019-01-19 16:46:15

标签: python go

我试图将Python脚本转换为Golang,只是为了查看性能差异并帮助我更多地学习Golang。

在Python中,我有2个脚本。一个是运行无限循环并在重新运行之前休眠一分钟的脚本。该代码检查服务器上的端点并读取输出,然后确定是否需要执行任何操作。如果是这样,它将处理输出并启动一个新的子进程。子进程是另一个Python脚本,它执行大量计算并创建数百个线程。在任何给定时间都可以运行多个子流程,它们对于不同的用户而言都是不同的任务。

我已经从API读取了Golang代码,并且可以开始新的子流程了。但是我不太确定如何去做。

我知道创建新的子流程(或与Go等效的任何东西)时,我可以创建一堆Go例程,但实际上我只是停留在“子流程”位上。

我尝试使用Go例程代替子流程,但是我不认为这是可行的方法?

根据可视化的要求,我添加了代码示例。

api.py:

while True:
    someparameter = 'randomIDfromdatabase'
    subprocess.Popen(["python3", "mycode.py", someparameter])
    time.sleep(60)

mycode.py

parameter = sys.argv[1]
for i in range(0, 100):
    thread.append(MyClass(parameter))
    thread.start()

我基本上需要Golang的“ subprocess.Popen”。

1 个答案:

答案 0 :(得分:0)

您可以使用Go os/exec包进行类似子流程的行为。例如,这是一个琐碎的程序,它在子进程中运行date程序并报告其stdout:

package main

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

func main() {
    out, err := exec.Command("date").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("The date is %s\n", out)
}

一个更有趣的示例from gobyexample,该示例显示了如何与已启动进程的stdio / stdout交互:

package main

import "fmt"
import "io/ioutil"
import "os/exec"

func main() {

    // We'll start with a simple command that takes no
    // arguments or input and just prints something to
    // stdout. The `exec.Command` helper creates an object
    // to represent this external process.
    dateCmd := exec.Command("date")

    // `.Output` is another helper that handles the common
    // case of running a command, waiting for it to finish,
    // and collecting its output. If there were no errors,
    // `dateOut` will hold bytes with the date info.
    dateOut, err := dateCmd.Output()
    if err != nil {
        panic(err)
    }
    fmt.Println("> date")
    fmt.Println(string(dateOut))

    // Next we'll look at a slightly more involved case
    // where we pipe data to the external process on its
    // `stdin` and collect the results from its `stdout`.
    grepCmd := exec.Command("grep", "hello")

    // Here we explicitly grab input/output pipes, start
    // the process, write some input to it, read the
    // resulting output, and finally wait for the process
    // to exit.
    grepIn, _ := grepCmd.StdinPipe()
    grepOut, _ := grepCmd.StdoutPipe()
    grepCmd.Start()
    grepIn.Write([]byte("hello grep\ngoodbye grep"))
    grepIn.Close()
    grepBytes, _ := ioutil.ReadAll(grepOut)
    grepCmd.Wait()

    // We ommited error checks in the above example, but
    // you could use the usual `if err != nil` pattern for
    // all of them. We also only collect the `StdoutPipe`
    // results, but you could collect the `StderrPipe` in
    // exactly the same way.
    fmt.Println("> grep hello")
    fmt.Println(string(grepBytes))

    // Note that when spawning commands we need to
    // provide an explicitly delineated command and
    // argument array, vs. being able to just pass in one
    // command-line string. If you want to spawn a full
    // command with a string, you can use `bash`'s `-c`
    // option:
    lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
    lsOut, err := lsCmd.Output()
    if err != nil {
        panic(err)
    }
    fmt.Println("> ls -a -l -h")
    fmt.Println(string(lsOut))
}

请注意,goroutine与子流程无关。 Goroutines是一种在单个Go进程中同时执行多项操作的方法。就是说,在与子流程进行交互时,goroutine通常会派上用场,因为它们有助于等待子流程完成,同时还可以在启动(主)程序中执行其他操作。但是,此细节非常针对您的应用程序。