2012-06-26 39 views
4

我有多線程的Python程序。主線程響應用戶的命令:從子線程中斷主線程的raw_input()

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()

回答

1

您可以使用類似select的東西來檢查sys.stdin何時有輸入。這使得循環不等待raw_input,而是輪詢,而你可以有一個循環條件來檢查是否退出循環。

+2

''select''只適用於Posix。 – SmartElectron