Skip to main content
 首页 » 编程设计

python之如何从 python 操作 cmd.exe,以便输出显示在 cmd.exe 窗口中

2025年05月04日9yyy_WW

我想使用 python 打开 cmd.exe,然后向 cmd.exe 依次发送几个命令,并在同一个 cmd.exe 窗口中查看输出。我怎样才能做到这一点? 使用以下代码不会在 cmd.exe 窗口中显示输出。

proc = subprocess.Popen("cmd", creationflags=subprocess.CREATE_NEW_CONSOLE) 
proc.communicate("dir\n") 

请您参考如下方法:

您需要指定 stdin=subprocess.PIPE, stdout=subprocess.PIPE。 (如果要捕获标准错误输出,还需指定 stderr=subprocess.PIPE)。否则,Popen.communicate 无法将输入发送到子进程,也无法获得输出。

import subprocess 
proc = subprocess.Popen("cmd", stdin=subprocess.PIPE, stdout=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_CONSOLE) 
out, err = proc.communicate("dir\n" "cd ..\n" "dir\n") 
# `Popen.communicate` returns a tuple of (standard output, standard error) 
print(out)