I want to be able to fetch a list of files without blocking, but i didn't see a way to do that in the documentation. Is the best way to do this in a executor?
Runtime Error: Event Loop is closed Problem Usually, this error can be fixed by replacing the asyncio. run() command with the command asyncio. new_event_loop(). run_until_complete() .
SIGTERM signals. This function cancels all tasks and then closes the event loop. when I send signal. SIGTERM(kill 'pid').
asyncio. get_event_loop () Get the current event loop. If there is no current event loop set in the current OS thread, the OS thread is main, and set_event_loop() has not yet been called, asyncio will create a new event loop and set it as the current one.
aiofiles is an Apache2 licensed library, written in Python, for handling local disk files in asyncio applications. Ordinary local file IO is blocking, and cannot easily and portably made asynchronous.
Yes, I think that's the best way. There is no native non-blocking call to list files that I'm aware of, so you've got no choice but to run the blocking call in a thread/subprocess to get non-blockiing behavior. Here's a simple example using ProcessPoolExecutor
.
import concurrent.futures
import asyncio
import os
def list_files():
return os.listdir(".")
def on_got_files(fut):
print("got files {}".format(fut.result()))
loop.stop()
def main():
with concurrent.futures.ProcessPoolExecutor() as executor:
fut = loop.run_in_executor(executor, list_files)
fut.add_done_callback(on_got_files)
print("Listing files asynchronously")
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.call_soon(main)
loop.run_forever()
Output:
C:\Users\Dan\Desktop>python3 async.py
Listing files asynchronously
got files [<files are listed here>]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With