动态获取python中subprocess.run()的输出
我希望在python中运行许多shell命令,并希望动态输出它们(类似于bash中的输出方式) 为此,我使用了:动态获取python中subprocess.run()的输出,python,subprocess,Python,Subprocess,我希望在python中运行许多shell命令,并希望动态输出它们(类似于bash中的输出方式) 为此,我使用了: import subprocess cmd=''' x=1 while [ $x -le 5 ]; do echo "$x" x=$(( $x + 1 )) sleep 2 done ''' out=subprocess.run(cmd, check=True, shell=True,stdin=PIPE, stdout=PIPE, stderr=STDOUT)
import subprocess
cmd='''
x=1
while [ $x -le 5 ]; do
echo "$x"
x=$(( $x + 1 ))
sleep 2
done
'''
out=subprocess.run(cmd,
check=True, shell=True,stdin=PIPE, stdout=PIPE, stderr=STDOUT)
out.stdout
问题:
os.system
李>
您可以使用
Popen
from subprocess import Popen, PIPE
cmd = '''
x=1
while [ $x -le 5 ]; do
echo "$x"
x=$(( $x + 1 ))
sleep 2
done
'''
out = Popen(
cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE
).communicate()[0].decode("utf-8")
print(out)
您可以使用
Popen
from subprocess import Popen, PIPE
cmd = '''
x=1
while [ $x -le 5 ]; do
echo "$x"
x=$(( $x + 1 ))
sleep 2
done
'''
out = Popen(
cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE
).communicate()[0].decode("utf-8")
print(out)
您可以使用
子进程。检查输出()
:
您可以使用
子进程。检查输出()
:
很抱歉,输出出来时,我看不到输出正在打印(即等待时间为2秒)。是因为我在jupyter/Ipyton?嗯,我真的不知道,但我得到了结果。它打印出了数字。我在终端中再次测试了它,它返回相同的结果。我的主要观点是动态获取输出,而不是在评估结束时获取所有输出。也就是说,我会看到打印的数字是2秒,intervalIt正在等待10秒。我猜是因为你给cmd写了5封信。5*2=10秒,完全正确。但我的问题是如何在打印时获取输出,而不是让
Popen
,或子流程等待完整的计算运行。我现在看到了同样的问题抱歉,但我看不到输出输出出来时正在打印(即等待2秒)。是因为我在jupyter/Ipyton?嗯,我真的不知道,但我得到了结果。它打印出了数字。我在终端中再次测试了它,它返回相同的结果。我的主要观点是动态获取输出,而不是在评估结束时获取所有输出。也就是说,我会看到打印的数字是2秒,intervalIt正在等待10秒。我猜是因为你给cmd写了5封信。5*2=10秒,完全正确。但我的问题是如何在打印时获取输出,而不是让Popen
,或子流程等待完整的计算运行。我现在明白了,他们也有同样的问题