【问题标题】:Why can Nodejs do file I/O async while Python asyncio can't?为什么 Nodejs 可以异步执行文件 I/O 而 Python asyncio 不能?
【发布时间】:2017-03-08 08:44:44
【问题描述】:

最近我想在本地文件 IO 上使用 Python async/await,但是在阅读以下链接后我发现这是不可能的:

Does asyncio supports asynchronous I/O for file operations?

Read file line by line with asyncio

解决方案是基于线程的 aiofiles 模块。但是在 Nodejs 中,仅使用基于标准 POSIX 函数的 fs 模块来使文件 IO 异步变得如此完美和容易。为什么nodejs可以做I/O异步,python却做不到?

【问题讨论】:

  • Nodes 并不一定比 Python 做更多的“asyncio”。 Nodejs 所做的是捆绑了一个 FS/IO API,默认情况下,它鼓励在 IO 调用上使用异步模式
  • asyncio 并非设计用于执行异步文件 I/O。在 python 中还有其他库可以做到这一点。例如aiofiles,它使用 fs API 扩展了 asyncio。

标签: python node.js asynchronous


【解决方案1】:

但是Node.js的异步文件I/O也是基于线程的:

请注意,除了 fs.FSWatcher() 和那些 显式同步使用libuv的线程池,可以有 对某些人来说令人惊讶和负面的性能影响 应用程序,请参阅 UV_THREADPOOL_SIZE 文档了解更多信息 信息。

– 来自https://nodejs.org/api/fs.html#fs_threadpool_usage

所以 Node.js fs API 与 Python asyncio + aiofiles 模块做同样的事情。

【讨论】:

    【解决方案2】:

    像这样使用多线程:

    import threading
    t = threading.Thread(target=method, name='LoopThread')
    t.start()
    t.join()
    

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 2015-07-24
      • 1970-01-01
      • 2015-01-17
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多