【发布时间】:2022-01-11 23:54:33
【问题描述】:
我尝试了以下两种方法来使用 subprocess.PIPE 读取另一个命令的实时输出,但只有其中一种在生成时为我提供输出,而另一种在命令终止后为我提供输出。我怎么理解?
用于从 subprocess.PIPE 读取的 python 脚本
脚本.py
import subprocess, shlex
from datetime import datetime
command = './loopWithSleep.sh' # or command = './loopWithSleep.py'
print('command used is', shlex.split(command))
# invoke process
process = subprocess.Popen(shlex.split(command),shell=True,stdout=subprocess.PIPE)
# Poll process.stdout to show stdout live
while True:
output = process.stdout.readline()
if process.poll() is not None:
break
if output:
print(output.strip())
print(datetime.now())
方法1(命令是bash脚本)
loopWithSleep.sh 是
#!/bin/bash
for i in $(seq 1 5); do
echo "iteration" $i
sleep 1
done
当我运行 python 脚本 script.py 时,我看到它按预期工作,每行之间有 1 秒的延迟
command used is ['./loopWithSleep.sh']
b'iteration 1'
2021-12-06 11:44:09.764482
b'iteration 2'
2021-12-06 11:44:10.770432
b'iteration 3'
2021-12-06 11:44:11.774778
b'iteration 4'
2021-12-06 11:44:12.782742
b'iteration 5'
2021-12-06 11:44:13.792413
方法2(命令为python脚本)
loopWithSleep.py 是
#! /usr/bin/python3
import time
for i in range(1, 6):
print('Iteration %d'%i)
time.sleep(1)
当我运行 python 脚本 script.py 时,我看到进程被阻塞,直到所有输出都可用并且子进程终止。您可以看到所有输出行都是在同一时间打印的,如我打印的时间戳所示。
command used is ['./loopWithSleep.py']
b'Iteration 1'
2021-12-06 11:46:38.234695
b'Iteration 2'
2021-12-06 11:46:38.234839
b'Iteration 3'
2021-12-06 11:46:38.234877
b'Iteration 4'
2021-12-06 11:46:38.234913
b'Iteration 5'
2021-12-06 11:46:38.234944
bash echo 和 python print 有什么区别,方法 1 在输出可用时立即打印,而方法 2 一次全部打印?
【问题讨论】:
标签: python python-3.x bash shell subprocess