How do I list files in Asyncio?
python, python-asyncio
Solution
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>]
Problem
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?