繁体   English   中英

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

[英]Interrupting main thread's raw_input() from child thread

我有多线程的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

解决方案1:我尝试了thread.interrupt_main() ,但它没有用。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM