Writing files asynchronously

前端 未结 1 1266
猫巷女王i
猫巷女王i 2021-01-02 16:42

I\'ve been trying to create a server-process that receives an input file path and an output path from client processes asynchronously. The server does some database-reliant

1条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 16:54

    You are missing an await before out.write() and out.flush():

    import asyncio
    from pathlib import Path
    
    import aiofiles as aiof
    
    FILENAME = "foo.txt"
    
    
    async def bad():
        async with aiof.open(FILENAME, "w") as out:
            out.write("hello world")
            out.flush()
        print("done")
    
    
    async def good():
        async with aiof.open(FILENAME, "w") as out:
            await out.write("hello world")
            await out.flush()
        print("done")
    
    
    loop = asyncio.get_event_loop()
    
    server = loop.run_until_complete(bad())
    print(Path(FILENAME).stat().st_size)  # prints 0
    
    server = loop.run_until_complete(good())
    print(Path(FILENAME).stat().st_size)  # prints 11
    

    However, I would strongly recommend trying to skip aiofiles and use regular, synchronized disk I/O, and keep asyncio for network activity:

    with open(file, "w"):  # regular file I/O
        async for s in network_request():  # asyncio for slow network work. measure it!
            f.write(s) # should be really quick, measure it!
    

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题