在 python 中运行一个子进程,并且都“实时"显示输出;并将其保存到变量 [英] Run a subprocess in python and both show the output in "real time" and save it to a variable

查看:42
本文介绍了在 python 中运行一个子进程,并且都“实时"显示输出;并将其保存到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从 python 代码运行一个子进程,并且都可以实时查看输出,并且一旦进程完成,输出就在一个变量中

I would like to be able to run a subprocess from python code and both see the output in real time and once the process is finished have the output in a variable

现在我只做两件事之一

1) 使用 subprocess.call 运行子进程,在这种情况下,我实时获得输出,但最后我没有变量中的输出(我想解析它并从中提取值)

1) Run subprocess using subprocess.call in that case I get the output in real time but I don't have at the end the output in a variable (I want to parse it and extract values from it)

2) 使用 subprocess.check_output 运行子进程,在这种情况下,我将输出放在一个变量中,但如果我想查看它,则必须手动"打印它

2) Run subprocess using subprocess.check_output in that case I have the output in a variable but if I want to see it then I have to print it "manually"

有没有办法把这两个东西放在一起"?

Is there a way to get both things "together" ?

希望清楚,如果您需要,我可以添加我的代码

Hope it is clear, I can add my code if you need

谢谢!!!

这是我当前的代码

我添加了一个超时可选参数(默认值为 1200 并且还处理 shell(出于某种原因,如果我没有 shell=True,在 Linux 中工作的相同命令在 Windows 中不起作用)模式"参数是我用来区分我想要实时"输出并且我不必解析它和其他情况的情况

I added a timeout optional parameter (Default value is 1200 and also deal with shell (For some reason same commands that work in Linux do not work in Windows if I don't have the shell=True) the "mode" parameter is the one that I use to differentiate the cases where I want the output in "real time" and I don't have to parse it and the other cases

我想知道是否有一种更干净、更好的方法来实现相同的结果

I was wondering if there is a cleaner and better way to achieve same results

推荐答案

import subprocess
from subprocess import PIPE

comd = input('command here : ')
comds = comd.split(' ')
f = subprocess.run(comds, shell= True,stdout=PIPE, stderr=PIPE)
result = f.stdout.decode()
errors = f.stderr.decode()

这篇关于在 python 中运行一个子进程,并且都“实时"显示输出;并将其保存到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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