问题描述
我尝试使用以下程序将 cmd.exe 包装在 windows 下,但它不起作用,它似乎在等待某些东西并且不显示任何内容.知道这里出了什么问题吗?
I try to wrap cmd.exe under windows with the following program but it doesn't work , it seems to wait for something and doesn't display anything. Any idea what is wrong here ?
import subprocess
process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write("dir\r\n")
output = process.stdout.readlines()
print output
推荐答案
这会锁定,因为 process.stdout.readlines()
读取进程的所有输出(直到它终止).由于 cmd.exe 仍在运行,它会一直等待它关闭.
This locks up because process.stdout.readlines()
reads all output by the process (until it terminates). Since cmd.exe is still running, it keeps waiting forever for it to close.
要解决此问题,您可以启动一个单独的线程来读取进程输出.如果您不调用 communicate()
,则无论如何都需要这样做,以避免可能的死锁.该线程可以重复调用process.stdout.readline()
,对数据进行处理或发送回主线程进行处理.
To fix this, you can start a separate thread to read the process output. This is something you need to do anyway if you don't call communicate()
, to avoid possible deadlock. This thread can call process.stdout.readline()
repeatedly and handle the data or send it back to the main thread for handling.
这篇关于用子进程包装 cmd.exe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!