Python:执行cmd命令时读取输出

问题描述 投票:0回答:1

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

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

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

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

python-3.x subprocess
1个回答
0
投票

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.