我需要在生成和运行子流程时显示一些进度条或其他内容.如何使用python做到这一点?import subprocesscmd = [python,wait.py]p = subprocess.Popen(cmd, bufsize=1024,stdin=subprocess.PIPE, stdout=subprocess...

我需要在生成和运行子流程时显示一些进度条或其他内容.
如何使用python做到这一点?
import subprocess
cmd = ['python','wait.py']
p = subprocess.Popen(cmd, bufsize=1024,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.stdin.close()
outputmessage = p.stdout.read() #This will print the standard output from the spawned process
message = p.stderr.read()
我可以使用此代码生成子流程,但是每过一秒钟我就需要打印出一些内容.
解决方法:
由于子进程调用处于阻塞状态,因此在等待时打印出某种内容的一种方法是使用多线程.这是使用threading._Timer的示例:
import threading
import subprocess
class RepeatingTimer(threading._Timer):
def run(self):
while True:
self.finished.wait(self.interval)
if self.finished.is_set():
return
else:
self.function(*self.args, **self.kwargs)
def status():
print "I'm alive"
timer = RepeatingTimer(1.0, status)
timer.daemon = True # Allows program to exit if only the thread is alive
timer.start()
proc = subprocess.Popen([ '/bin/sleep', "5" ])
proc.wait()
timer.cancel()
不相关的说明是,在使用多个管道时调用stdout.read()可能导致死锁.应该改用subprocess.communicate()函数.
沃梦达教程
本文标题为:python-在生成和运行子进程时显示进度


基础教程推荐
猜你喜欢
- 基于Python创建语音识别控制系统 2023-08-11
- python – Django使用登录的Windows域用户进行身份验证 2023-11-15
- python进程池:multiprocessing.pool 2023-09-04
- Python随机采样及概率分布(二) 2023-08-11
- python – 是否有可能重新编写子进程? 2023-11-16
- python subprocess模块 监控子进程的2种方式 忙等待和立即返回同时设置子进程超时 2023-09-04
- python中文件操作与异常的处理图文详解 2023-08-08
- Python命令行参数解析包argparse的使用详解 2022-10-20
- GraphLab-Create Module未安装在Python 3.5(ubuntu)上 2023-11-13
- 详解LyScript 内存扫描与查壳实现 2022-10-20