我有一个小型python服务器来完成以下工作:
高级代码是这样的(只是抽象它,因为详细的代码太长,无法在这里复制):
# A global queue is initialized to cache user inputs
command_queue = Queue.Queue()
# This is the background-thread running bash script based on user's input
class command_runner(Thread):
def run(self):
user_command = command_queue.get()
# code to run bash script specified in user_command, using Popen
class main_program(object):
def listen_user_input(self):
command_runner.start()
while True:
user_input = raw_input("Please input command:")
command_queue.put(user_input)我注意到,当后台线程(command_runner)运行一些bash脚本时,主程序的raw_input有时不响应任何用户输入。raw_input似乎被卡住了。
其他一些可能有帮助的资料:
发布于 2018-05-01 19:39:47
尝试将stdin=subprocess.PIPE添加到Popen调用中:
Popen(..., stdin=subprocess.PIPE, ...)默认情况下, inherits its parent's file descriptors,包括stdin。您将显式地为它提供一个新的stdout和stderr,而不是一个新的stdin,因此它是从您的主要stdin进程继承的。我的猜测是,stdin被子进程捕获(即使该进程不需要),阻止对raw_input的调用接收输入,直到Popen进程完成并返回对stdin的控制之后才返回。
如果进程可能尝试从stdin读取,并且您不打算向该管道写入任何内容,您也可以让它从/dev/null (在linux上)中提取,使用如下所示:
Popen(..., stdin=open('/dev/null', 'rb').fileno(), ...)这将使它能够(不能)在不悬挂的情况下从stdin上读出来。
https://stackoverflow.com/questions/50121993
复制相似问题