如何在Python中仅暂停脚本的一部分

2024-05-14 22:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python中的time.sleep()管理有一些问题。我想在脚本的第二部分中使用一些值,但它们必须彼此延迟300毫秒,我只想延迟脚本的这一部分,而不是所有其他部分。这些值是摄影机检测到的对象的X坐标。脚本如下所示:

while True:
       if condition is True:
             print(xvalues)
             time.sleep(0.3)
       
       if another_condition is True:
             #do other stuff and:
             np.savetxt('Xvalues.txt', xvalues)
 

在脚本的第二部分(“做其他事情”),我将用检测到的X坐标编写G代码行,并将它们发送到CNC机器。如果在脚本的该位置写入time.sleep(),while循环中的所有内容都将延迟。
如何在不影响脚本其余部分的情况下提取一些一次采样300毫秒的值


Tags: 对象脚本trueiftimeisanothersleep
2条回答
from threading import Thread


class sleeper(Thread):
    if condition is True:
        print(xvalues)
        time.sleep(0.3)

class worker(Thread):
    if another_condition is True:
        #do other stuff and:
        np.savetxt('Xvalues.txt', xvalues)

def run():
    sleeper().start()
    worker().start()

您可以将300ms检查作为处理condition的一部分

第一次检测condition时,获取并记住变量中的当前时间

下次condition再次为真时,请检查它是否比上次condition为真时长300毫秒以上

大概是这样的:

last_condition_time=None
while True:
       if condition is True:
          if not last_condition_time or more_than_300ms_ago(last_condition_time):
             print(xvalues)
             last_condition_time = get_current_time()
       
       if another_condition is True:
             #do other stuff and:
             np.savetxt('Xvalues.txt', xvalues)
 

相关问题 更多 >

    热门问题