Skip to content

Python运行.exe程序脚本无法正常停止

问题

  • 问题表现:

    1. 用 python 运行.exe 程序,针对这个程序发送 c 命令,正确执行。发送 q 命令可以退出.exe 程序,但是实际这个 python 脚本仍然在运行。
    2. 使用communicate() 后不能向.exe程序发送多个命令
  • 报错信息:程序不能正常停止

产生的原因

  1. 使用的subprocess.Pepen()执行的.exe程序:在使用subprocess.Popen()时,要确保你处理了所有的文件流(stdin、stdout 和 stderr),否则可能会导致子进程挂起
  2. 使用communicate() 方法,communicate() 方法调用一次后就会关闭

解决方法

  1. 使用stdin.write方法(这个方法不会返回向.exe 执行命令后的信息。)
  2. 结合readline()读取一下输出出来
output = proc.stdout.readline().strip()
    print(output.decode('utf-8'))

原文链接:https://ceshiren.com/t/topic/31702