当前位置: > > > > Golang相当于在Python中创建子进程
Golang相当于在Python中创建子进程
来源:stackoverflow
2024-04-19 20:27:33
0浏览
收藏
从现在开始,努力学习吧!本文《Golang相当于在Python中创建子进程》主要讲解了等等相关知识点,我会在米云中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!
问题内容
我正在尝试将 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()
我基本上需要相当于“subprocess.popen”的 golang。
解决方案
您可以使用 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)
}
一个更有趣的示例 ,展示了如何与已启动进程的 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 进程中同时执行多项操作的方法。也就是说,在与子进程交互时,goroutines 通常会派上用场,因为它们有助于等待子进程完成,同时还在启动(主)程序中执行其他操作。但具体细节取决于您的应用程序。
今天关于《Golang相当于在Python中创建子进程》的内容介绍就到此结束,如果有什么疑问或者建议,可以在米云公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
