【问题标题】:PYTHON subprocess cmd.exe closes after first commandPYTHON 子进程 cmd.exe 在第一个命令后关闭
【发布时间】:2015-08-20 20:10:30
【问题描述】:

我正在开发一个实现 cmd 窗口的 python 程序。 我正在使用带有 PIPE 的子进程。 例如,如果我写“dir”(通过标准输出),我使用communicate() 来从 cmd 获取响应,它确实有效。

问题是在一个while True循环中,这不会超过一次,似乎子进程会自行关闭.. 请帮帮我

import subprocess
process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
x=""
while x!="x":
    x = raw_input("insert a command \n")
    process.stdin.write(x+"\n")
    o,e=process.communicate()
    print o

process.stdin.close()

【问题讨论】:

标签: python cmd subprocess stdout stdin


【解决方案1】:

主要问题是当程序仍在运行但没有从标准输出读取的内容时尝试读取subprocess.PIPE 死锁。 communicate() 手动终止进程以停止此操作。

一种解决方案是将读取 stdout 的代码放在另一个线程中,然后通过 Queue 访问它,这允许通过超时而不是死锁在线程之间可靠地共享数据。

新线程将连续读取标准,当没有更多数据时停止。

将从队列流中抓取每一行,直到达到超时(队列中没有更多数据),然后将行列表显示到屏幕上。

此过程适用于非交互式程序

import subprocess
import threading
import Queue

def read_stdout(stdout, queue):
    while True:
        queue.put(stdout.readline()) #This hangs when there is no IO

process = subprocess.Popen('cmd.exe', shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
q = Queue.Queue()
t = threading.Thread(target=read_stdout, args=(process.stdout, q))
t.daemon = True # t stops when the main thread stops
t.start()

while True:
    x = raw_input("insert a command \n")
    if x == "x":
        break
    process.stdin.write(x + "\n")
    o = []
    try:
        while True:
            o.append(q.get(timeout=.1))
    except Queue.Empty:
        print ''.join(o)

【讨论】:

  • 哇!这很好用!我不知道python中的队列..现在我学会了,这太棒了。非常感谢。和平
  • @Guy 不客气!只要知道这个队列不仅仅是一个常规的队列数据结构,而是一个用于多线程的“同步队列”。
  • 不确定它是否只是 Python 3.X 的东西,但我必须将universal_newlines=True 作为Popen() 的参数包含在内。除此之外,这正是我几个小时以来一直在寻找的东西,谢谢!
猜你喜欢
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
  • 2020-11-26
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
相关资源
最近更新 更多