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

Rob*_*Rob 16 python

对不起,这可能是一个可怕的问题.我JUST今天开始学习蟒蛇.我一直在阅读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
Run Code Online (Sandbox Code Playgroud)

甚至更好:

import sys
time = sys.argv[1]
while there is still time left:
    #run this block
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.此外,非常感谢其他在线指南和教程.我真的很喜欢Python的Byte.但是,深入Python并不能引起我的注意.我想我应该把它搞砸了,并且更加努力地阅读那个.

Eli*_*ght 18

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

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.
Run Code Online (Sandbox Code Playgroud)

当所有非守护程序线程都退出时,Python解释器将关闭.因此,当您的主线程退出时,如果运行的唯一其他线程是您在单独的守护程序线程中运行的任务,那么Python将退出.如果您希望能够退出而不必担心手动导致它退出并等待它停止,这是在后台运行某些东西的便捷方式.

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


Eta*_*oin 14

尝试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()
Run Code Online (Sandbox Code Playgroud)

因此,只要我们开始的时间小于用户指定的最大值,我们就会循环.这并不完美:最值得注意的是,如果do_stuff()需要很长时间,我们将不会停止直到它完成,我们发现我们已经过了我们的截止日期.如果您需要能够在时间过后立即中断正在进行的任务,则问题会变得更加复杂.

  • 当然!这样可以正常工作 - 您只需要确保在小块执行之间运行该测试. (2认同)

joh*_*all 5

如果您使用的是 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'
Run Code Online (Sandbox Code Playgroud)