【问题标题】:End python code after 60 seconds60秒后结束python代码
【发布时间】:2013-12-25 18:25:01
【问题描述】:

下面是一些功能齐全的代码。

我计划通过命令行执行此代码,但我希望它在 60 秒后结束。

有谁知道最好的解决方法?

提前致谢。

import time
class listener(StreamListener):

    def on_data(self, data):
        try:
            print data
            saveFile = open('twitDB.csv','a')
            saveFile.write(data)
            saveFile.write('\n')
            saveFile.close()
            return True
        except BaseException, e:
            print 'failed ondata,' ,str(e)
            time.sleep(5)

    def on_error(self, status):
        print status

【问题讨论】:

  • 记住开始的时间,在on_data查询时间,过了一分钟就退出?
  • 开头的'import time'是在记时间吗?我也找不到查询时间的代码...
  • 这只是一个类定义。它不会“从命令行运行”。你的意思是来自python解释器?
  • 不要抓到BaseException,除非你以后重新加注。为什么要忽略SystemExitKeyboardInterrupt
  • 基本上我希望代码每小时运行一分钟,我想我会先在 60 秒后取消代码,然后查看使用命令行,以便代码每小时运行一次。这不正确吗?

标签: python


【解决方案1】:

您可以将您的代码移动到一个守护线程并在 60 秒后退出主线程:

#!/usr/bin/env python
import time
import threading

def listen():
    print("put your code here")

t = threading.Thread(target=listen)
t.daemon = True
t.start()

time.sleep(60)
# main thread exits here. Daemon threads do not survive.

【讨论】:

  • failed ondata, global name 'listen' is not defined 是我收到的错误消息
  • @user3102640:我已经更新了代码。如果有不清楚的地方请告诉我。
  • 我在这里不断收到语法错误:` print("put your code here")` @J.F Sebastian
  • @user3102640:代码在 Python 2 和 Python 3 上按原样工作。确保复制粘贴过程没有在代码中添加 Unicode 空格(只需删除 print 之前的空格并键入 4手动空格)。
  • 这很好,@J.F.Sebastian。
【解决方案2】:

试试这个:

import os
import time
from datetime import datetime
from threading import Timer

def exitfunc():
    print "Exit Time", datetime.now()
    os._exit(0)

Timer(5, exitfunc).start() # exit in 5 seconds

while True: # infinite loop, replace it with your code that you want to interrupt
    print "Current Time", datetime.now()
    time.sleep(1)

这个 StackOverflow 问题中还有更多示例:Executing periodic actions in Python

我认为不鼓励使用os._exit(0),但我不确定。关于这件事的一些事情感觉不洁。不过,它确实有效。

【讨论】:

  • 代码运行良好,插入上述代码,但 end 函数没有结束。
  • 现在试试吧,os._exit(0) 会按照您的意愿退出。
  • 跑了 5 秒,所以到了那里,:D
  • 没有出什么问题,现在只是重复打印日期。
  • @user3102640: os._exit() 是一个核选项,但它有效。另见How to exit the entire application from a Python thread?
【解决方案3】:

我希望这是一种定期执行函数并在 60 秒后结束的简单方法:

import time
import os
i = 0
def executeSomething():
 global i
 print(i)
 i += 1
 time.sleep(1)
 if i == 10:
    print('End')
    os._exit(0)


while True:
 executeSomething()

【讨论】:

    【解决方案4】:

    使用signal.ALARM 在指定时间后收到通知。

    import signal, os
    
    def handler(signum, frame):
        print '60 seconds passed, exiting'
        cleanup_and_exit_your_code()
    
    # Set the signal handler and a 60-second alarm
    signal.signal(signal.SIGALRM, handler)
    signal.alarm(60)
    
    run_your_code()
    

    从您的示例来看,代码究竟会做什么、如何运行以及它将迭代什么样的循环并不明显。但是您可以轻松实现ALARM 信号,以便在超时到期后得到通知。

    【讨论】:

    • 我收到此错误消息failed ondata, 'module' object has no attribute 'SIGALRM'
    • @user: signal.SIGALRM 无法在某些平台上运行,例如 Windows。
    【解决方案5】:

    这是我最喜欢的超时方式。

    def timeout(func, args=None, kwargs=None, TIMEOUT=10, default=None, err=.05):
        if args is None:
            args = []
        elif hasattr(args, "__iter__") and not isinstance(args, basestring):
            args = args
        else:
            args = [args]
    
        kwargs = {} if kwargs is None else kwargs
    
        import threading
        class InterruptableThread(threading.Thread):
            def __init__(self):
                threading.Thread.__init__(self)
                self.result = None
    
            def run(self):
                try:
                    self.result = func(*args, **kwargs)
                except:
                    self.result = default
    
        it = InterruptableThread()
        it.start()
        it.join(TIMEOUT* (1 + err))
        if it.isAlive():
            return default
        else:
            return it.result
    

    【讨论】:

    • 这是对此处代码的修改。 code.activestate.com/recipes/473878
    • 你实际上并没有打断func(*args, **kwargs) 的电话。无论是否发生超时,它都会继续运行。此外,错误命名的“InterruptableThread”不是守护进程。如果func() 仍在运行,它将阻止程序退出。
    • @J.F.Sebastian 您如何使用daemon 完成这项工作,以便func() 会超时?换句话说,您能否修改您的答案,以便是否可以像我的答案一样采用函数和参数?
    • @J.F.Sebastian 如何使用该语法将结果输出?我还没有弄清楚。
    • @J.F.Sebastian 基本上,我仍在寻找我提出的这个问题的有效答案,stackoverflow.com/q/20360795/2246694 将包含daemon
    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 2019-06-03
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多