繁体   English   中英

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

[英]How to run x command for y seconds when condition is met in Python?

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

示例:秒= 10

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

它只应打印问候10秒钟,然后继续。

如何在Python中实现?

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

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

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

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次:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM