从子线程中断主线程的raw_input()

时间:2012-06-26 11:12:55

标签: python multithreading

我有多线程的Python程序。主线程响应用户的命令:

while 1:
    try:
        cmd = raw_input(">> ")
        if cmd == "exit":
            break
        # other commands
    except KeyboardInterrupt:
        break

# other stuffs

问题:如何从其他子线程中断while循环?

sys.exit()不是一个选项,因为while循环之外还有其他代码。

我想到的可能的解决方案:

  1. 中断主线程
  2. 将“退出”写入sys.stdin
  3. 解决方案1:我尝试了thread.interrupt_main(),但它没有用。

    解决方案2:调用sys.stdin.write()将无效,以下代码:

    f = open(sys.stdin.name, "w")
    f.write("exit")
    f.close()
    

    Another similar question提供了一个答案,建议您生成另一个进程并使用subprocess.Popen.communicate()向其发送命令。但是不可能对当前流程本身进行communicate()吗?

1 个答案:

答案 0 :(得分:1)

您可以使用select之类的内容来检查sys.stdin上何时有输入。这使循环不等待raw_input,而是轮询,而你可以有一个循环条件来检查是否退出循环。

相关问题