这个程序应该立即回显 sleep 的 pid:
import subprocess
subprocess.check_output("sleep 1 & echo $!", shell=True)
直接在 shell 上运行它,它立即打印 pid,但在 python 中运行它,它&
被忽略并且在echo
执行之前需要 1 秒。
我怎样才能让它只在一次执行check_output
(或另一个函数subprocess
)时起作用?
(这是一个简化的例子,实际上sleep 1
我没有放置自己的可执行文件)
check_output
等待输出管道关闭并sleep
拥有它们。您可以重定向到/dev/null
立即返回。
subprocess.check_output("sleep 1 >/dev/null 2>&1 & echo $!", shell=True)
更新
很难判断是否sleep 1
真的在后台运行,所以我写了一个稍微大一点的测试。
test.py - 写入时间stdout
为 5 秒
import time
for i in range(5):
print(time.strftime('%H:%M:%S'), flush=True)
time.sleep(1)
print('done', flush=True)
runner.py - 运行重定向stdout
到文件的测试并监控文件。
import subprocess as subp
import time
import os
# run program in background
pid = int(subp.check_output("python3 test.py >test.out 2>&1 & echo $!",
shell=True))
print("pid", pid)
# monitor output file
pos = 0
done = False
while not done:
time.sleep(.1)
if os.stat('test.out').st_size > pos:
with open('test.out', 'rb') as fp:
fp.seek(pos)
for line in fp.readlines():
print(line.strip().decode())
done = b'done' in line
pos = fp.tell()
print("test complete")
运行它,我明白了
td@mintyfresh ~/tmp $ python3 runner.py
pid 24353
09:32:18
09:32:19
09:32:20
09:32:21
09:32:22
done
test complete
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句