是的,我认为这是最好的方式.我所知道的列表文件没有本地非阻塞调用,所以你别无选择,只能在线程/子进程中运行阻塞调用以获得非阻塞行为.这是使用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()
输出:
C:\Users\Dan\Desktop>python3 async.py
Listing files asynchronously
got files []