如何在Python中传递5秒后使函数返回?

alw*_*btc 5 python time function

我想编写一个函数,该函数将在5秒后返回:

def myfunction():
    while passed_time < 5_seconds:
        do1()
        do2()
        do3()
        .
        .
    return
Run Code Online (Sandbox Code Playgroud)

我的意思是,此功能仅运行5秒钟,在5秒钟后,它应结束并继续使用其他功能:

myfunction()
otherfunction()   ----> This should start 5 seconds after myfunction() is executed.
Run Code Online (Sandbox Code Playgroud)

最好的祝福

Eri*_*ric 5

你可以做:

def myfunction():
    start = time.time()
    while time.time() < start + 5:
        do1()
        do2()
        do3()
Run Code Online (Sandbox Code Playgroud)

请注意,这将至少在5秒-如果do1do2do3每次取3秒,那么这个功能将需要9秒


如果你想myFunction在这些调用之间切断,你可以这样做:

def myfunction():
    todo = itertools.cycle([do1, do2, do3])
    start = time.time()
    while time.time() < start + 5:
        todo.next()()
Run Code Online (Sandbox Code Playgroud)

这种情况需要6s