【发布时间】:2011-07-21 16:08:06
【问题描述】:
我需要运行一个程序并将其输出收集到标准输出。这个程序(socat)需要在 python 脚本的持续时间内在后台运行。 Socat 运行后会处于 dameon 模式,但首先它会向标准输出输出一些我在脚本的其余部分需要的行。
命令:socat -d -d PTY: PTY:
输出:
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 读取。
【问题讨论】:
-
没有
&是否可以工作? -
不 :( 遗憾的是,它只是挂起。
-
您是否尝试过添加打印语句以验证它在您调用
Popen后被阻塞,而不是在调用read()时被阻塞? -
socat 会产生很多输出,还是只有几行?
标签: python