我需要运行一个程序并将其输出收集到标准输出。该程序 (socat) 需要在 python 脚本运行期间在后台运行。 Socat 一旦运行就会处于守护进程模式,但首先它会将一些行输出到标准输出,我的脚本的其余部分需要这些行。
命令:socat -d -d PTY: PTY:
Output:
2011/03/23 21:12:35 socat[7476] N PTY is /dev/pts/1
2011/03/23 21:12:35 socat[7476] N PTY is /dev/pts/2
2011/03/23 21:12:35 socat[7476] N starting data transfer loop with FDs [3,3] and [5,5]
...
我基本上想在程序开始时运行它并让它运行直到脚本终止,但我需要将两个 /dev/pts/X 名称读入 python 中。
谁能告诉我该怎么做?
我想出了这个,它只是挂起,我猜是因为它阻止了子进程的终止。
#!/usr/bin/python
from subprocess import Popen, PIPE, STDOUT
cmd = 'socat -d -d PTY: PTY: &'
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
output = p.stdout.read()
# Process the output
print(output)
谢谢你的帮助
编辑:似乎它可能会写入 stderr,但脚本仍然只是在有或没有 & 甚至从 stderr 读取的情况下挂起。