• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在 python 运行子进程,并且都“实时"显示输出;并其保存到变量

用户头像
it1352
帮助1

问题说明

我希望能够从 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

正确答案

#1
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()

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhccjbbg
系列文章
更多 icon
同类精品
更多 icon
继续加载