实现Python`time`构造的最佳方法是什么?

时间:2016-02-13 12:32:25

标签: python python-3.x

假设您正在发射火箭。当你提升时,你需要根据给定的表来固定角度。但是,在某些时候,您需要执行一次性操作(如果它们是空的,则释放助推器,或者例如在某个高度放弃整流罩)。

我现在正在做的是:

fairing_jettisoned = False
while apogee < TARGET_APOGEE:
    aim_rocket(speed, altitude, apogee)
    if not fairing_jettisoned and altitude > FAIRING_ALT:
        jettison_fairing()
        fairing_jettisoned = True

这对于更复杂的例程来说非常繁琐,因为你必须来回跳跃。

其他语言有when语句(when altitude > FAIRING_ALT:),但在Python中不存在。

我尝试实现它的一种方法是使用类。这很hacky,但似乎运作良好:

class when(object):
    calls = {}
    def __init__(self, expr, func, *args, runs_left=1, **kwargs):
        _, fname, line, *_ = inspect.stack()[1]
        stored_instance = when.calls.get((fname, line), self)
        if stored_instance == self:
            self.func = func
            self.args = args
            self.kwargs = kwargs
            self.runs_left = runs_left
            when.calls[(fname, line)] = self
        self = stored_instance
        self.expr = expr
        if self.runs_left and self.expr:
            self.runs_left -= 1
            return self.func(*self.args, **self.kwargs

这可以像这样运行:

while apogee < TARGET_APOGEE:
    aim_rocket(speed, altitude, apogee)
    when(altitude > FAIRING_ALT, jettison_fairing)

最终,我想要的是拥有这种语法:

while apogee < TARGET_APOGEE:
    aim_rocket(speed, altitude, apogee)
    when(altitude > FAIRING_ALT, runs_left=3):
        # Do a bunch of things; no need for a lambda or function.
        jettison_fairing()

我也尝试使用__enter____exit__来实现它,但如果已经运行,我无法找到跳到__exit__的方法。 async / await可以实现这样的功能吗?或者是完全不同的东西?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用线程设置某些内容,例如:

from threading import Thread
import time, random

def when(condition, action) -> Thread:
    def threadtask():
        while not condition():
            time.sleep(0.5)
        action()
    t = Thread(target = threadtask)
    t.start()
    return t

altitude = 1
def jettison_fairing():
    print("Jettison the fairing!")
when(lambda: altitude > 500, jettison_fairing)
while altitude < 1000:
    time.sleep(1)
    altitude += random.randint(0,300)
    print("Altitude is now ",altitude)

# Output:

##Altitude is now  173
##Altitude is now  290
##Altitude is now  370
##Altitude is now  395
##Altitude is now  464
##Altitude is now  564
##Jettison the fairing!
##Altitude is now  736
##Altitude is now  762
##Altitude is now  1057

对于奖励积分,你可以写一个装饰者来做这件事。

然而。您所描述的是编程real-time systems所面临的一些问题。没有简单的“何时”构造可以解决您的问题。 “何时”对您意味着什么 - 例如,程序检查高度的频率如何?如果您的程序同时等待五十个不同的“何时”条件,那么哪些优先级更高?如果两个“何时”条件同时发生,并且一组代码告诉计算机抛弃整流罩而另一组假设它仍然存在,会发生什么?

相关问题