在不使用 for 循环的情况下在控制台上打印进度条 [英] Printing progress bar on a console without the use of for -loop

查看:48
本文介绍了在不使用 for 循环的情况下在控制台上打印进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 python 编写的脚本,其中有一个语句:

I have a script written in python, where I have a statement:

Process.open() //some parameters

执行命令并将输出放在控制台上,

Which executes a command and puts the output on the console ,

在不知道执行上述语句所花费的时间的地方,上面的语句会被一个函数调用来完成一系列命令的执行,并且完全没有像进度条"中的典型示例那样使用for循环在 python 示例中".

where I do not know the time taken to execute the above statement , the above statement will be called by a function to complete a series of command execution and there is no for loop used at all like in typical examples in "progress bar in python examples".

现在,我的问题是否可以打印进度条以显示这种情况下python中的1..100%等进度的完成情况?

Now , my question is it possible to print the progress bar to show the completion of progress like 1..100% in python for this scenario?

推荐答案

subprocess 模块允许您将管道附加到衍生进程的 stdout 和 stderr.这有点复杂,但是如果您非常了解该过程的输出,则可以以特定间隔轮询通过管道生成的输出,然后相应地增加进度条.再说一次,如果该进程无论如何都会生成控制台输出,为什么不在那里实现一个进度条?

The subprocess module allows you to attach pipes to the stdout and stderr of your spawned process. It's a bit complicated but if you know the output of that process very well, you can poll the output generated through the pipe at specific intervals and then increment a progressbar accordingly. Then again, if that process generates console output anyway, why not implement a progressbar there?

编辑以显示如何做到这一点.args 是一个包含您的命令及其参数的列表.

Edit to show how this could be done. args is a list with your command and its arguments.

import subprocess
sub = subprocess.Popen(args, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
while sub.poll() is None:
    output = sub.stdout.read() # get all of current contents
    if output:
        # ... process output and decide how far the process has advanced
        # ... advance your progressbar accordingly
    else:
        time.sleep(1E-01) # decide on a reasonable number of seconds to wait before polling again
if sub.returncode != 0:
    err = sub.stderr.read()
    # ... decide what to do

如果您可以修改子流程,我建议您在那里进行进度.

If you can modify the sub process I suggest you do the progress there.

这篇关于在不使用 for 循环的情况下在控制台上打印进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆