在Python中满足条件后,如何在y秒内运行x命令?

时间:2019-05-06 20:27:11

标签: python linux python-3.x

我有一个应用程序,我必须在y秒内运行命令,但前提是要满足条件。 持续时间一到,就应该移到下一行。

示例:Second = 10

if i==1:
    print("Hello") # for 10 seconds

它只应打个招呼10秒钟,然后继续前进。

如何在Python中实现这一目标?

2 个答案:

答案 0 :(得分:1)

只需在您的条件中添加一个时间循环:

import time
if i==1:
    starttime=time.time()
    while time.time() < (starttime+10):
        print("hello")

答案 1 :(得分:1)

我会稍微改变以前的答案:

import time
if i==1:
    starttime=time.time()
    while time.time() < (starttime+10):
        time.sleep(1) # <-- do not print hello too often !
        print("hello")

因为按照我的估计,它将打印“ hello”约10,345,123次:)