Python运行.exe程序脚本无法正常停止
问题
-
问题表现:
- 用 python 运行.exe 程序,针对这个程序发送 c 命令,正确执行。发送 q 命令可以退出.exe 程序,但是实际这个 python 脚本仍然在运行。
- 使用
communicate()
后不能向.exe
程序发送多个命令
- 报错信息:程序不能正常停止
产生的原因
- 使用的
subprocess.Pepen()
执行的.exe
程序:在使用subprocess.Popen()
时,要确保你处理了所有的文件流(stdin、stdout 和 stderr),否则可能会导致子进程挂起 - 使用
communicate()
方法,communicate()
方法调用一次后就会关闭
解决方法
- 使用
stdin.write
方法(这个方法不会返回向.exe 执行命令后的信息。) - 结合
readline()
读取一下输出出来
output = proc.stdout.readline().strip()
print(output.decode('utf-8'))