运行用户指定时间的Python脚本

20 投票
3 回答
30818 浏览
提问于 2025-04-15 22:41

我今天刚开始学习Python,正在看《Python小白书》。现在我有一个关于时间的Python项目,但在《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

3 个回答

6

如果你在使用Linux系统,并且想要中断一个运行时间很长的程序,可以使用signal这个命令:

import signal, time

def got_alarm(signum, frame):
    print 'Alarm!'

# call 'got_alarm' in two seconds:
signal.signal(signal.SIGALRM, got_alarm)
signal.alarm(2)

print 'sleeping...'
time.sleep(4)

print 'done'
16

试试 time.time(),这个函数会返回从一个叫做 epoch 的时间点开始到现在的秒数(对于很多电脑来说,这个时间点是1970年1月1日的午夜)。下面是一个使用它的方法:

import time

max_time = int(raw_input('Enter the amount of seconds you want to run this: '))
start_time = time.time()  # remember when we started
while (time.time() - start_time) < max_time:
    do_stuff()

我们会一直循环,直到从开始到现在的时间小于用户设定的最大时间。这种方法并不完美:最明显的问题是,如果 do_stuff() 这个函数执行得很慢,我们不会在它完成之前停止,这样就可能会超过我们设定的时间限制。如果你需要在时间到达时立即中断正在进行的任务,那就会变得更复杂。

26

我建议你可以启动一个新的线程,把它设置成守护线程,然后让它休眠,直到你想让这个任务结束为止。例如:

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的好处在于,你不需要把任务分成一个个小块,然后时不时检查一下时间是否到了。虽然这样做可能适合你的需求,但也可能会有问题,比如每个小块的执行时间很长,导致你的程序运行时间比用户输入的时间要长得多等等。是否会出现这个问题取决于你正在编写的任务,但我觉得提到这种方法可能对你更好。

撰写回答