[英]How to manipulate cmd.exe from python, so that the output is shown in the cmd.exe window
I want to open cmd.exe using python, then send several commands sequentially to the cmd.exe and see the output in the same cmd.exe window. 我想使用python打开cmd.exe,然后依次向cmd.exe发送几个命令,并在同一cmd.exe窗口中查看输出。 How can I do this? 我怎样才能做到这一点? Using the following code doesn't show the output in the cmd.exe window. 使用以下代码不会在cmd.exe窗口中显示输出。
proc = subprocess.Popen("cmd", creationflags=subprocess.CREATE_NEW_CONSOLE)
proc.communicate("dir\n")
You need to specify stdin=subprocess.PIPE, stdout=subprocess.PIPE
. 您需要指定stdin=subprocess.PIPE, stdout=subprocess.PIPE
。 (Also specify stderr=subprocess.PIPE
if you want to catch standard error output). (如果要捕获标准错误输出,还请指定stderr=subprocess.PIPE
)。 Otherwise, Popen.communicate
can't send input to subprocess, and can't get output. 否则, Popen.communicate
无法将输入发送到子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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.