我今天刚开始学习Python。我一直在读《Python 简明》。现在我有一个Python项目,需要时间。我在 Byte of Python 中找不到任何与时间相关的内容,所以我会问你:
如何运行一个块一段用户指定的时间然后中断?
例如(在一些伪代码中):
time = int(raw_input('Enter the amount of seconds you want to run this: '))
while there is still time left:
#run this block
甚至更好:
import sys
time = sys.argv[1]
while there is still time left:
#run this block
我建议再生成一个thread http://docs.python.org/library/threading.html#thread-objects,使其成为守护线程 http://docs.python.org/library/threading.html#threading.Thread.daemon, then sleeping http://docs.python.org/library/time.html#time.sleep直到你想让任务死掉为止。例如:
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.
当所有非守护线程退出时,Python 解释器将关闭。因此,当你的主线程退出时,如果唯一运行的其他线程是你在单独的守护线程中运行的任务,那么 Python 将退出。如果您希望能够退出而不必担心手动导致其退出并等待其停止,那么这是在后台运行某些内容的便捷方法。
换句话说,这种方法相对于使用sleep
在 for 循环中,在这种情况下,您必须以将任务分解为离散块的方式对任务进行编码,然后经常检查时间是否到了。这可能适合您的目的,但它可能会出现问题,例如每个块花费大量时间,从而导致您的程序运行时间明显长于用户输入的时间等。这对您来说是否是一个问题取决于您正在编写的任务,但我想我会提到这种方法,以防它对您更好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)