Is there an easy way in Python to wait until certain condition is true?
Unfortunately the only possibility to meet your constraints is to periodically poll, e.g....:
import time
def wait_until(somepredicate, timeout, period=0.25, *args, **kwargs):
mustend = time.time() + timeout
while time.time() < mustend:
if somepredicate(*args, **kwargs): return True
time.sleep(period)
return False
or the like. This can be optimized in several ways if somepredicate
can be decomposed (e.g. if it's known to be an and
of several clauses, especially if some of the clauses are in turn subject to optimization by being detectable via threading.Event
s or whatever, etc, etc), but in the general terms you ask for, this inefficient approach is the only way out.
Waiting until the desired condition is met in python
Try this1:
import time
def list(self):
command = ["<application_command>", "list"]
status = False
start = time.time()
while True: # while status is false
status = "running" in self.execute(command)
if ((time.time() - start) >= 60) and status:
return
if status: # if the status is true
return status
else:
continue
1: from the ShadowRanger's comment
Write a Python function that waits and listens until a condition is met, similar to WebDriverWait().until()
This might be difficult to generalise in the way you're thinking about it. Often, you don't want to wait for things. It's better to do other stuff or do nothing. Python has an entire library dedicated to handling this kind of thing. it's called asyncio.
Conceptually, all you need a function that will tell you if some action is complete, and a while loop.
import time
while not action_is_complete():
sleep(10)
This will keep going until action_is_complete()
returns true
. Then your program will continue executing.
How to create a function to wait until a boolean value becomes true
wait_until(lambda: block.distance_to(pygame.mouse.get_pos()) <= 100)
This creates a function that can be called as many times as needed, to evaluate your condition.
Python Asyncio - Pythonic way of waiting until condition satisfied
Using of asyncio.Event
is quite straightforward. Sample below.
Note: Event should be created from inside coroutine for correct work.
import asyncio
async def bg_tsk(flag):
await asyncio.sleep(3)
flag.set()
async def waiter():
flag = asyncio.Event()
asyncio.create_task(bg_tsk(flag))
await flag.wait()
print("After waiting")
asyncio.run(waiter())
Related Topics
Pandas - How to Compare 2 CSV Files and Output Changes
Calculate Monthly Returns from Daily Returns in Pandas(Cumpound)
Swapping Columns in a Numpy Array
How to Block Comment Code in the Ipython Notebook
How to Print Superscript in Python
Python Pandas Count the Number of Occurances Inside Lists in a Column
How to Delete a Column That Contains Only Zeros in Pandas
How to Convert List into String With Quotes in Python
Type Conversion in Python Attributeerror: 'Str' Object Has No Attribute 'Astype'
Printing Even Characters With Strings in Python
Pip Install Pandas: Installing Dependencies Error
Running a Powershell Cmdlet in a Python Script
How to Execute a Script Remotely in Python Using Ssh
Creating Random Pairs from Lists
Python MySQL Connector: Caching_Sha2_Password Plugin