Python:在执行 cmd 命令时读取输出 [英] Python: read output while executing cmd commands

查看:56
本文介绍了Python:在执行 cmd 命令时读取输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 子进程模块执行 cmd 命令.执行此 cmd 命令(例如,运行一些批处理文件、.exe 文件)正在打开新的命令提示符窗口.如何使用python读取新打开的cmd窗口的输出?

I am executing cmd commands using python subprocess module. Execution of this cmd commands (eg., running some batch file, .exe file) are opening new command prompt window. How to read output of newly open cmd window using python?

我正在使用以下代码来执行用户提供的命令:

I am using following code to execute commands provided by user:

process = subprocess.Popen(command, cwd = working_directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

我正在使用 process.communicate() 方法来读取输出.但是,它只允许我读取现有命令提示符窗口的输出.如果用户提供触发新命令提示符窗口的命令,那么如何读取该窗口的输出?

I am using process.communicate() method to read the output. However it is allowing me to read output of the existing command prompt window only. If user is providing command which triggers new command prompt window, then how to read output of that window?

推荐答案

下面的代码打开一个新的命令提示符,在那里执行命令并显示该命令窗口的输出

Below code opens a new command prompt, execute a command there and display the output of that command window

from subprocess import Popen,CREATE_NEW_CONSOLE,PIPE

# /K option tells cmd to run the command and keep the command window from closing. You may use /C instead to close the command window after the 

command='cmd /C help'
proc=Popen(command,creationflags=CREATE_NEW_CONSOLE,stdout=PIPE)
output=proc.communicate()[0]
print ('').join(output)

这篇关于Python:在执行 cmd 命令时读取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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