繁体   English   中英

Golang相当于在Python创建一个子进程

[英]Golang equivalent of creating a subprocess in Python

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

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

我已经从 API 读取了我的 Golang 代码,它已准备好开始一个新的子进程。 但我不太确定我 go 是怎么弄的。

我知道当我创建了新的子进程(或者它是 Go 等价物)时,我可以创建一堆 Go 例程,但实际上我只是停留在“子进程”位上。

我曾尝试使用 Go 例程代替子进程,但我认为这不是通往 go 的方式吗?

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

api.py:

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

我的代码.py

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

我基本上需要 Golang 等同于“subprocess.Popen”。

您可以将 Go os/exec包用于类似子进程的行为。 例如,这是一个在子进程中运行date程序并报告其标准输出的简单程序:

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)
}

一个来自 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))
}

请注意,goroutines 与子进程关系不大。 Goroutines 是一种在单个 Go 进程中同时做多项事情的方法 也就是说,当与子进程交互时,goroutines 通常会派上用场,因为它们有助于等待子进程完成,同时还在启动(主)程序中做其他事情。 但这些细节非常特定于您的应用程序。

https://github.com/estebangarcia21/子进程

消毒模式

package main

import (
    "log"

    "github.com/estebangarcia21/subprocess"
)

func main() {
    s := subprocess.New("ls", subprocess.Arg("-lh"))

    if err := s.Exec(); err != nil {
        log.Fatal(err)
    }
}

Shell模式

package main

import (
    "log"

    "github.com/estebangarcia21/subprocess"
)

func main() {
    s := subprocess.New("ls -lh", subprocess.Shell)

    if err := s.Exec(); err != nil {
        log.Fatal(err)
    }
}

暂无
暂无

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

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