【发布时间】:2019-03-20 02:39:45
【问题描述】:
我想将在 cmd 中运行的 python 脚本的输出获取到主机脚本中的 variable。我部分能够做到,但没有得到想要的输出。请大家在否决和关闭这个问题之前,请注意这与关于同一问题的其他问题不同
这是我编写的需要运行的脚本代码:
import click #-->pip install click
import sys
import time
#number of iterations taken
iters = 5
#record the starting time
start = time.time()
#iterate through loop
for j in range(1, iters + 1):
print(f"iteration {j} out of {iters}.")
#Generate progressbar
with click.progressbar(range(1)) as bar:
for i in bar:
pass
#End of Progressbar
#Record the Ending time
end = time.time()
print(f"Execution took approximately {round((end-start), 3)} seconds") #print the time taken rounded off to 3 decimals
这是我需要的输出(我在本地运行脚本时得到输出):
iteration 1 out of 5.
[####################################] 100%
iteration 2 out of 5.
[####################################] 100%
iteration 3 out of 5.
[####################################] 100%
iteration 4 out of 5.
[####################################] 100%
iteration 5 out of 5.
请注意,每次在屏幕上打印新字符时,我都希望将输出存储在我的变量中。即实时。
这是我使用子进程编写的用于获取文件输出的代码:
import subprocess
from subprocess import run, PIPE
cmd = 'python iter.py'
output = subprocess.run(cmd, shell=True, universal_newlines=True, stdout=PIPE, stderr=PIPE) #variable that i want to store the value in.
print(output.stdout)
但不幸的是,它只输出这个:
iteration 1 out of 5.
iteration 2 out of 5.
iteration 3 out of 5.
iteration 4 out of 5.
iteration 5 out of 5.
Execution took approximately 0.001 seconds
显然,我丢失了我的进度条!,这对我的工作至关重要!我如何确保即使是进度条也存储在变量中。
注意 - 我非常需要将输出存储在一个变量中,以便将来可以引用它。
【问题讨论】:
-
请帮帮我!
-
你试过
subprocess.check_output吗? docs.python.org/3/library/… -
是的,先生,我已经使用了 check_output 功能,但我还不能让进度条显示出来!
-
那你为什么不手动添加进度条呢?
标签: python cmd subprocess output popen