> ") if cmd == "exi-6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:55:42 27 4
gpt4 key购买 nike

我有一个多线程 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()

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

最佳答案

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

关于python - 从子线程中断主线程的 raw_input(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11206093/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com