Home > database >  How to pause only one part of the script in Python
How to pause only one part of the script in Python

Time:10-15

I have some issues with time.sleep() management in Python. I would like to use some values in a second part of the script, but they have to be delayed 300 ms one from another and I want to delay only that part of the script and not all the rest. These values are the X coordinates of an object detected by a camera. The script is something like this:

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)
 

In the second part of the script (#do other stuff), I will write G-code lines with the X-coordinate detected and send them to a CNC machine. If I write a time.sleep() in that position of the script, everything in the while loop will be delayed.
How can I extract some values sampled 300ms a time without influencing the rest of the script?

CodePudding user response:

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()

CodePudding user response:

You can include the 300ms checking as part of handling condition.

The first time you detect condition, get and remember the current time in a variable.

The next time condition is true again, check that it's more than 300ms from the last time the condition was true.

Something like this:

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)
 
  • Related