繁体   English   中英

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

[英]Running a Python script for a user-specified amount of time

我今天刚开始学习Python。 我一直在阅读Python的Byte。 现在我有一个涉及时间的Python项目。 我在Python的Byte中找不到任何与时间有关的内容,所以我会问你:

如何在用户指定的时间内运行一个块然后中断?

例如(在一些伪代码中):

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

我建议生成另一个线程 ,使其成为一个守护程序线程 ,然后睡觉直到你想让任务死掉。 例如:

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的优势在于,在这种情况下,你必须以一种方式对任务进行编码,使其分解成离散的块,然后经常检查你的时间是否已经结束。 哪个可能适合您的目的,但它可能有问题,例如每个块需要花费大量时间,从而导致程序运行的时间比用户输入的时间长得多等。这对您来说是否有问题取决于你正在写的任务,但我想我会提到这种方法,以防它对你更好。

尝试time.time() ,它返回当前时间,作为自称为纪元的设定时间(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,并且想要中断长时间运行的进程,请使用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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM