![](/img/trans.png)
[英]How to manage the exit of a process without blocking its thread in Python?
[英]python exit a blocking thread?
在我的代碼中,我循環通過raw_input()
來查看用戶是否已請求退出。 我的應用程序可以在用戶退出之前退出,但我的問題是應用程序仍處於活動狀態,直到我輸入一個鍵從阻塞函數raw_input()
。 我可以通過發送假輸入來強制raw_input()
返回嗎? 我可以終止它所在的線程嗎? (它擁有的唯一數據是一個名為wantQuit
變量)。
你為什么不把線程標記為守護進程?
來自文檔 :
線程可以標記為“守護程序線程”。 這個標志的意義在於,當只剩下守護進程線程時,整個Python程序都會退出。 初始值繼承自創建線程。 可以通過守護程序屬性設置標志。
您可以使用非阻塞功能來讀取用戶輸入。
此解決方案是特定於Windows的:
import msvcrt
import time
while True:
# test if there are keypresses in the input buffer
while msvcrt.kbhit():
# read a character
print msvcrt.getch()
# no keypresses, sleep for a while...
time.sleep(1)
要在Unix中做類似的事情,它一次讀取一行,不像windows版本通過char讀取char(感謝Aaron Digulla提供了python用戶論壇的鏈接):
import sys
import select
i = 0
while i < 10:
i = i + 1
r,w,x = select.select([sys.stdin.fileno()],[],[],2)
if len(r) != 0:
print sys.stdin.readline()
你可以使用這個包裝你的功能的超時功能。 這里的食譜來自: http : //code.activestate.com/recipes/473878/
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
'''This function will spwan a thread and run the given function using the args, kwargs and
return the given default value if the timeout_duration is exceeded
'''
import threading
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return it.result
else:
return it.result
Python郵件列表上有一篇文章解釋了如何在Unix上執行此操作:
# this works on some platforms:
import signal, sys
def alarm_handler(*args):
raise Exception("timeout")
def function_xyz(prompt, timeout):
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout)
sys.stdout.write(prompt)
sys.stdout.flush()
try:
text = sys.stdin.readline()
except:
text = ""
signal.alarm(0)
return text
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.