在 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()
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhccjbbg
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
检查邮件是否发送成功
it1352 07-25 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20