【问题标题】:Redirect output of a command made in cmd to a variable in Python 3将 cmd 中命令的输出重定向到 Python 3 中的变量
【发布时间】: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


【解决方案1】:

进度条只会在终端显示。

https://click.palletsprojects.com/en/7.x/api/#click.progressbar

默认情况下,如果文件不是终端,则不会渲染此进度条。

【讨论】:

  • 你知道如何实时存储输出吗?即 cmd 输出中的每个更改都应该在变量中实时更改。
  • 不知道。但是关于这个还有很多其他的问题。 stackoverflow.com/questions/17411966/…
  • 非常感谢先生!上帝保佑你帮了我很多!
猜你喜欢
  • 2012-07-05
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 2012-05-06
  • 2011-12-15
  • 2016-09-09
  • 2021-09-09
相关资源
最近更新 更多