يخرج بيثون موضوع حظر؟
-
23-08-2019 - |
سؤال
في الرمز الخاص بي أنا حلقة رغم ذلك raw_input()
لمعرفة ما إذا كان المستخدم قد طلب الإقلاع عن التدخين. يمكن أن يتم إنهاء التطبيق الخاص بي قبل إنهاء المستخدم، لكن مشكلتي هو التطبيق لا يزال حيا حتى أخرج مفتاحا للعودة من وظيفة الحظر raw_input()
. وبعد هل يمكنني القيام به raw_input()
للعودة عن طريق إرسالها بإدخال مزيف؟ هل يمكنني إنهاء الخيط الذي هو عليه؟ (البيانات الوحيدة لها هي متغير واحد يسمى wantQuit
).
المحلول
يمكنك استخدام هذه المهلة الوظيفة التي تلتف وظيفتك. إليك الوصفة من: 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 بأكمله يخرج عند ترك خيوط الخفي فقط. يتم تورث القيمة الأولية من خيط الخلق. يمكن ضبط العلم من خلال سمة الخفي.
يمكنك استخدام وظيفة غير حظر لقراءة إدخال المستخدم.
هذا الحل هو محدد 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 (بفضل 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/134892/
هناك المشاركة على قائمة بريد بايثون الذي يفسر كيفية القيام بذلك ل 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