我如何在 python 子进程中使用睡眠功能
how can i use sleep function in python subprocess
executor.py
from time import sleep
if __name__ == "__main__"
for i in range(10):
print(i)
sleep(1)
starter.py
from subprocess import Popen, PIPE
if __name__ == "__main__"
process = Popen(['python', 'executor.py'], stdout=PIPE, universal_newlines=True)
while process.poll() is None:
output = process.stdout.readline()
print(output)
process.wait()
在Shell
python starter.py
命令执行后结果如下
#after 10秒后....
0
1个
2个
3个
4个
5个
6个
7
8个
9
我要打印每一个 second
我该如何解决这个问题?
缓冲标准输出。您应该在每个 print
:
之后刷新缓冲区
from time import sleep
import sys
if __name__ == "__main__":
for i in range(10):
print(i)
sys.stdout.flush()
sleep(1)
executor.py
from time import sleep
if __name__ == "__main__"
for i in range(10):
print(i)
sleep(1)
starter.py
from subprocess import Popen, PIPE
if __name__ == "__main__"
process = Popen(['python', 'executor.py'], stdout=PIPE, universal_newlines=True)
while process.poll() is None:
output = process.stdout.readline()
print(output)
process.wait()
在Shell
python starter.py
命令执行后结果如下
#after 10秒后....
0
1个
2个
3个
4个
5个
6个
7
8个
9
我要打印每一个 second
我该如何解决这个问题?
缓冲标准输出。您应该在每个 print
:
from time import sleep
import sys
if __name__ == "__main__":
for i in range(10):
print(i)
sys.stdout.flush()
sleep(1)