为用户指定数量的tim运行Python脚本

2024-06-11 08:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我今天刚开始学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

Tags: 项目run用户内容字节timeissys
3条回答

尝试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()需要很长时间,我们不会停下来,直到它结束,我们发现我们已经过了最后期限。如果你需要在时间一过就中断正在进行的任务,问题就会变得更加复杂。

如果您在Linux上,并且希望中断长时间运行的进程,请使用信号

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'

我建议生成另一个thread,使其成为daemon thread,然后sleeping,直到您希望任务死亡。例如:

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将退出。这是一种在后台运行的方便方法,如果您希望能够直接退出而不必担心手动导致它退出并等待它停止。

换言之,这种方法相对于在for循环中使用sleep的优点是,在这种情况下,您必须以这样的方式对任务进行编码,以便将其分解成离散的块,然后每隔一段时间检查一下您的时间是否已到。对于您的目的来说,这可能是好的,但是它可能会有问题,比如每个块占用了大量的时间,从而导致您的程序运行的时间比用户输入的要长得多,等等。对于您来说,这是否是个问题取决于您正在编写的任务,但是我想我会提到这种方法,以防对你更好。

相关问题 更多 >