子进程:在后台启动进程,在上启动另一个进程

2024-03-29 14:48:30 发布

您现在位置:Python中文网/ 问答频道 /正文

此程序应立即响应休眠的pid:

import subprocess
subprocess.check_output("sleep 1 & echo $!", shell=True)

在shell上直接运行它,它会立即打印pid,但是在python中运行它时,&被忽略,在执行echo之前需要1秒的时间。在

我怎样才能只执行一次check_output(或{}的另一个函数)?在

(这是一个简化的示例,实际上,我没有sleep 1我将自己的可执行文件放进去)


Tags: 函数importecho程序true可执行文件示例output
1条回答
网友
1楼 · 发布于 2024-03-29 14:48:30

check_output等待输出管道关闭,sleep也有输出管道。您可以重定向到/dev/null立即返回。在

subprocess.check_output("sleep 1 >/dev/null 2>&1 & echo $!", shell=True)

更新

很难说sleep 1是否真的在后台运行,所以我写了一个稍微大一点的测试。在

测试.py-将时间写入stdout5秒

^{pr2}$

跑步者.py-运行重定向到文件的测试并监视该文件。在

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

相关问题 更多 >