Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
让Python保持循环语句运行,并每3秒检查一次条件_Python_Python 3.x_Loops_While Loop - Fatal编程技术网

让Python保持循环语句运行,并每3秒检查一次条件

让Python保持循环语句运行,并每3秒检查一次条件,python,python-3.x,loops,while-loop,Python,Python 3.x,Loops,While Loop,我希望保持循环条件语句运行,但并不总是检查条件 例如,如果条件为true,则在接下来的3秒钟内,循环的条件语句将运行,然后在第3秒钟后检查条件,然后重复此过程 我不想等待或睡眠三秒,我想让我的循环工作三秒。然后检查它是否应该像@RemcoGerlich所提到的那样继续三年 while if_active() == True: #check the condition every 3 seconds` try: # it will keep running

我希望保持循环条件语句运行,但并不总是检查条件

例如,如果条件为true,则在接下来的3秒钟内,循环的条件语句将运行,然后在第3秒钟后检查条件,然后重复此过程

我不想等待或睡眠三秒,我想让我的循环工作三秒。然后检查它是否应该像@RemcoGerlich所提到的那样继续三年

while if_active() == True:    #check the condition every 3 seconds` 
   try:               # it will keep running in 3 seconds if if_active() is true  
       with open(masterpath, 'r') as f:
            s = f.read()
        exec(s)

您可以使用sleep之类的命令来避免连续运行。您可以在这个线程中看到一个更详细的答案:

这里有一个有趣的异步方式。只是为了好玩,有一个
activate
ing的演示

import signal, os
import time

def handler(signum, frame):
    for i in range(3):
        print("foo bar")
        time.sleep(0.1)
    signal.alarm(3)

# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)

while True:
    try:
        active = not active
        if not active:
            signal.alarm(0)
        time.sleep(60)
    except KeyboardInterrupt as interrupt:
        # demonstrating activate, with ctrl+c
        signal.alarm(3)

您可以跟踪上一次检查的时间,并且只有在经过三秒后才能重新检查

from datetime import datetime, timedelta

INTERVAL = timedelta(minutes=3)
last_checked = datetime.now() - INTERVAL

while True:
    now = datetime.now()
    if last_checked <= (now - INTERVAL):
        if not if_active():
            break
        last_checked = now

    # do your thing here
    pass
从datetime导入datetime,timedelta
间隔=时间增量(分钟=3)
上次检查=datetime.now()-间隔
尽管如此:
now=datetime.now()

如果上次选中,请修复您的缩进。除非您使用操作系统中的某些东西使您的进程进入睡眠状态,否则等待3秒钟是没有意义的。否则,即使在您等待的时候,它也会继续消耗CPU。您是说读取文件并运行
exec
需要三秒钟吗?用
而if\u active()==True:
替换
而if\u active():
更为惯用。我觉得每个人都误解了他的问题。他不想等待或睡眠三秒钟,他希望他的循环工作三秒钟。然后检查它是否应该再继续三次。他的if_active()检查会去哪里?添加了activate。
时间。sleep()
当然可以,但是如果
exec(s)
运行(随机)需要0到3秒之间的任何时间,则循环总时间会变为3到6秒(如果
exec(s)),则所有赌注都会被取消
所需时间超过3秒)。不幸的是,OP未能澄清他们到底想要什么,这使得这个问题模棱两可,所有答案都可能是正确的。如果最后检查的
在3秒内,它似乎会被更新。我想它应该在3秒钟后更新。最后一件事,initial
Last\u checked
应该是
datetime。now()
@Andy:那要看情况了,在这种情况下,如果第一次激活它就不会运行了。