【问题标题】:How can I run a certain function for a specific time in Python?如何在 Python 中运行特定时间的某个函数?
【发布时间】:2011-03-01 17:04:48
【问题描述】:

例如,我有函数 do_something(),我希望它运行 1 秒(而不是 0.923 秒。它不会这样做。但是 0.999 是可以接受的。)

但是,do_something 必须准确运行 1 秒是非常重要的。我正在考虑使用 UNIX 时间戳并计算秒数。但我真的很想知道 Python 是否有办法以更美观的方式做到这一点......

函数do_something() 是长时间运行的,必须在一秒后中断。

【问题讨论】:

  • 会不会总是花不到一秒的时间,而且您需要填充它?它会花费超过一秒钟,而您想减少它吗?
  • 请澄清您的问题。你想 (a) 运行一次 do_something 恰好 1 秒然后中断它,还是 (b) 你想重复运行 do_something 直到 1 秒过去,或者 (c) 你想运行 @ 987654325@ 重复直到 1 秒过去在 1 秒过去时中断最近的执行?
  • no do_something() 函数只是做了一些事情......但是它必须只做它正在做的事情只有一秒钟。如果是 1 秒,它必须切断它正在做的事情。
  • @JohnRoach:那么选项(a)呢?
  • @JohnRoach:我已从您的问题中删除了 while 循环,因为我认为它使人们认为您在选择 (b) 或 (c) 选项。

标签: python real-time


【解决方案1】:

我从 cmets 得知这里某处有一个 while 循环。这是一个子类Thread 的类,基于threading 模块中_Timer 的源代码。我知道你说过你决定不使用线程,但这只是一个计时器控制线程; do_something 在主线程中执行。所以这应该是干净的。 (如果我错了,有人纠正我!):

from threading import Thread, Event

class BoolTimer(Thread):
    """A boolean value that toggles after a specified number of seconds:

    bt = BoolTimer(30.0, False)
    bt.start()
    bt.cancel() # prevent the booltimer from toggling if it is still waiting
    """

    def __init__(self, interval, initial_state=True):
        Thread.__init__(self)
        self.interval = interval
        self.state = initial_state
        self.finished = Event()

    def __nonzero__(self):
        return bool(self.state)

    def cancel(self):
        """Stop BoolTimer if it hasn't toggled yet"""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.state = not self.state
        self.finished.set()

你可以这样使用它。

import time

def do_something():
    running = BoolTimer(1.0)
    running.start()
    while running:
        print "running"              # Do something more useful here.
        time.sleep(0.05)             # Do it more or less often.
        if not running:              # If you want to interrupt the loop, 
            print "broke!"           # add breakpoints.
            break                    # You could even put this in a
        time.sleep(0.05)             # try, finally block.

do_something()

【讨论】:

    【解决方案2】:

    Python 的“sched”模块看起来很合适:

    http://docs.python.org/library/sched.html

    除此之外:Python 不是一种实时语言,它通常也不在实时操作系统上运行。所以你的要求有点可疑。

    【讨论】:

    • “Python 不是一种实时语言”我知道我知道......当一种语言被强迫给我时,我讨厌它。这真的不是我的选择。我会检查时间表。看起来很有希望。
    • 所以你是说基本上我应该为每个步骤简单地安排我的功能?
    【解决方案3】:

    这段代码可能对你有用。描述听起来像你想要的:

    http://programming-guides.com/python/timeout-a-function

    它依赖于 python signal 模块:

    http://docs.python.org/library/signal.html

    【讨论】:

    • 实际上,signals 模块不是 unix-only,但 SIGALRM 信号是。但是,如果您 上使用 unix,这将是一个完美的解决方案。特别是如果您无法控制 do_something 的内容。
    • 很遗憾,该网站的链接现在已损坏 - 已被域名人质服务捕获:(
    猜你喜欢
    • 2018-07-13
    • 2021-12-09
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 2022-11-30
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多