我建议生成另一个线程,使其成为守护程序线程,然后休眠直到您希望任务终止。例如:
from time import sleep
from threading import Thread
def some_task():
while True:
pass
t = Thread(target=some_task) # run the some_task function in another
# thread
t.daemon = True # Python will exit when the main thread
# exits, even if this thread is still
# running
t.start()
snooziness = int(raw_input('Enter the amount of seconds you want to run this: '))
sleep(snooziness)
# Since this is the end of the script, Python will Now exit. If we
# still had any other non-daemon threads running, we wouldn't exit.
# However, since our task is a daemon thread, Python will exit even if
# it's still going.
@H_502_4@
当所有非守护程序线程都退出时,Python解释器将关闭。因此,当您的主线程退出时,如果唯一正在运行的其他线程是您在单独的守护程序线程中运行的任务,则Python将会退出。如果您希望能够退出而无需担心手动导致退出并等待其停止,则这是在后台运行某些内容的便捷方法。
因此,换句话说,这种方法相对于sleep@H_502_4@在for循环中使用的优势在于,在这种情况下,您必须以这样的方式对任务进行编码:将任务分解为离散的块,然后每隔一段时间检查一次时间是否到了。可能对您的目的而言很好,但是它可能会有问题,例如每个块是否花费大量时间,从而导致程序的运行时间远长于用户输入的时间,等等。取决于您正在编写的任务,但是我想我会提到这种方法,以防对您更好。