首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当另一个线程运行时,raw_input不响应用户输入

当另一个线程运行时,raw_input不响应用户输入
EN

Stack Overflow用户
提问于 2018-05-01 18:40:36
回答 1查看 110关注 0票数 0

我有一个小型python服务器来完成以下工作:

  • 主线程使用raw_input获取用户输入;
  • 另一个线程(即后台线程)由主线程启动,以执行与用户输入相对应的任务。作业都是作为bash脚本编写的,所以这个线程使用subprocess.Popen来运行脚本。

高级代码是这样的(只是抽象它,因为详细的代码太长,无法在这里复制):

代码语言:javascript
复制
# 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似乎被卡住了。

其他一些可能有帮助的资料:

  • command_running运行的bash脚本是长时间运行的,但不重(通常为10分钟)。因此,当raw_input被卡住时,机器不会耗尽资源。
  • 有些脚本可以使用"ssh -q some_command 2>&1“将ssh发送到其他计算机(因此ssh命令正在静悄悄地运行)。
  • bash脚本的所有stdout和stderr都通过"Popen(user_command,stderr=sys.stdout.fileno(),stdout=log_fp)“重定向到文件中。
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-01 19:39:47

尝试将stdin=subprocess.PIPE添加到Popen调用中:

代码语言:javascript
复制
Popen(..., stdin=subprocess.PIPE, ...)

默认情况下, inherits its parent's file descriptors,包括stdin。您将显式地为它提供一个新的stdoutstderr,而不是一个新的stdin,因此它是从您的主要stdin进程继承的。我的猜测是,stdin被子进程捕获(即使该进程不需要),阻止对raw_input的调用接收输入,直到Popen进程完成并返回对stdin的控制之后才返回。

如果进程可能尝试从stdin读取,并且您不打算向该管道写入任何内容,您也可以让它从/dev/null (在linux上)中提取,使用如下所示:

代码语言:javascript
复制
Popen(..., stdin=open('/dev/null', 'rb').fileno(), ...)

这将使它能够(不能)在不悬挂的情况下从stdin上读出来。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50121993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档