[英]Python execv and pipe output
I'd like to use Python's os.execv
to replace my current process, but I also want the new process to send stdout
to another process (to collect logs and ship them over the network). 我想使用Python的
os.execv
替换当前的进程,但是我还希望新进程将stdout
发送到另一个进程(收集日志并通过网络发送它们)。 The process collecting logs also needs to be started by the original Python process. 收集日志的过程也需要由原始Python进程启动。
I'm guessing I need to do some fork, dup2, execv stuff, but I need some help. 我猜我需要做一些fork,dup2,execv之类的事情,但是我需要一些帮助。
In bash, it might look something like this 在bash中,它可能看起来像这样
#!/bin/bash
exec ./foo ∣ ./bar
You can set up the pipe and processes this way. 您可以通过这种方式设置管道并进行处理。
import os
(read_fd, write_fd) = os.pipe()
pid = os.fork()
if pid == 0:
os.dup2(read_fd, 0)
os.close(read_fd)
os.close(write_fd)
os.execlp('./bar', './bar')
os._exit(-1) # in case exec fails
os.close(read_fd)
os.dup2(write_fd, 1)
os.close(write_fd)
os.execlp('./foo', './foo')
It's still convenient to use subprocess
though, at least for the first part. 至少在第一部分中,使用
subprocess
仍然很方便。
import os
import subprocess
p = subprocess.Popen(['./bar'], stdin=subprocess.PIPE)
os.dup2(p.stdin.fileno(), 1)
p.stdin.close()
os.execlp('./foo', './foo')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.