在concurrent.futures 内部,第一个示例将shutil.copy 生成到处理池中。
也许值得考虑ThreadPoolExecutor 和ProcessPoolExecutor (no GIL) 之间的区别
import shutil
with ThreadPoolExecutor(max_workers=4) as e:
e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
e.submit(shutil.copy, 'src4.txt', 'dest4.txt')
如上所述here (async versions of shutil)
@graingert (an author) cmets 方法在异步引擎内部创建托管线程。不幸的是,这似乎只适用于 v3.9
https://docs.python.org/3.9/library/asyncio-task.html#asyncio.to_thread
当然有
await asyncio.to_thread(shutil.copyfile, "a", "b")
@xyloguy建议
正如(也)提到的here (async versions of shutil)
如果您使用的 python 版本早于 3.9(我是),您可以使用 aiofiles.os.wrap,其实现与 @pwwang mention in their comment 相同。否则我会同意按照@graingert 的建议使用 asyncio.to_thread。
import shutil
from aiofiles.os import wrap
copyfile = wrap(shutil.copyfile)
copyfileobj = wrap(shutil.copyfileobj)
await copyfile(src, dst)
为什么以前的答案不充分
大部分答案都忽略了问题的异步部分。
我想你可能会有一个在线程完成后解决的未来,但是......
在异步系统中使用线程可能会破坏异步引擎解决这些未来的好处。考虑异步引擎将操作分解为并行期货的情况,并希望在继续之前等待所有这些都解决,您的线程将独立运行且不受引擎管理。我们通过使用上面提供的示例来避免这个问题。
tl;博士
最理想的情况是,我们希望智能引擎为我们完成这项工作。