Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list files in Asyncio? [closed]

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?

like image 901
leech Avatar asked May 27 '14 16:05

leech


People also ask

How do I fix a closed event loop?

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

How do I close all async IO tasks?

SIGTERM signals. This function cancels all tasks and then closes the event loop. when I send signal. SIGTERM(kill 'pid').

What is async IO Get_event_loop ()?

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.

What is Aiofiles?

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.


1 Answers

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>]
like image 197
dano Avatar answered Sep 23 '22 05:09

dano