亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python子流程:他們如何/何時關閉文件?

Python子流程:他們如何/何時關閉文件?

一只甜甜圈 2022-09-20 15:47:17
我想知道為什么子進程使這么多文件保持打開狀態。我有一個例子,其中某些文件似乎永遠保持打開狀態(在子進程完成后,甚至在程序崩潰之后)。請考慮以下代碼:import aiofilesimport tempfileasync def main():    return [await fds_test(i) for i in range(2000)]async def fds_test(index):    print(f"Writing {index}")    handle, temp_filename = tempfile.mkstemp(suffix='.dat', text=True)    async with aiofiles.open(temp_filename, mode='w') as fp:        await fp.write('stuff')        await fp.write('other stuff')        await fp.write('EOF\n')    print(f"Reading {index}")    bash_cmd = 'cat {}'.format(temp_filename)    process = await asyncio.create_subprocess_exec(*bash_cmd.split(), stdout=asyncio.subprocess.DEVNULL, close_fds=True)    await process.wait()    print(f"Process terminated {index}")if __name__ == "__main__":    import asyncio    asyncio.run(main())這將一個接一個地生成進程(按順序)。我希望同時打開的文件數量也是一個。但事實并非如此,在某些時候我得到以下錯誤:/Users/cglacet/.pyenv/versions/3.8.0/lib/python3.8/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)   1410             # Data format: "exception name:hex errno:description"   1411             # Pickle is not used; it is complex and involves memory allocation.-> 1412             errpipe_read, errpipe_write = os.pipe()   1413             # errpipe_write must not be in the standard io 0, 1, or 2 fd range.   1414             low_fds_to_close = []OSError: [Errno 24] Too many open files我嘗試在沒有該選項的情況下運行相同的代碼,但它仍然崩潰。這個答案表明,這可能是問題的根源,錯誤也指向線 。但這似乎不是問題所在(在沒有該選項的情況下運行會產生相同的錯誤)。stdout=asyncio.subprocess.DEVNULLerrpipe_read, errpipe_write = os.pipe()
查看完整描述

1 回答

?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

問題不是來自此代碼中的問題是 tempfile.mkstemp() 實際上打開了該文件:create_subprocess_exec

mkstemp() 返回一個元組,其中包含一個打開文件的操作系統級句柄(由 os.open()返回) ...

我以為它只會創建文件。為了解決我的問題,我只是在 中添加了一個調用。這消除了錯誤,但有點奇怪(打開文件兩次)。所以我把它改寫為:os.close(handle)

import aiofiles

import tempfile

import uuid



async def main():

    await asyncio.gather(*[fds_test(i) for i in range(10)])


async def fds_test(index):

    dir_name = tempfile.gettempdir()

    file_id = f"{tempfile.gettempprefix()}{uuid.uuid4()}"

    temp_filename = f"{dir_name}/{file_id}.dat"


    async with aiofiles.open(temp_filename, mode='w') as fp:

        await fp.write('stuff')


    bash_cmd = 'cat {}'.format(temp_filename)

    process = await asyncio.create_subprocess_exec(*bash_cmd.split(), close_fds=True)

    await process.wait()



if __name__ == "__main__":

    import asyncio

    asyncio.run(main())

現在我想知道為什么錯誤是由而不是引起的,也許是因為它子進程打開了更多的文件,以至于它不太可能使臨時文件創建成為打破限制的原因......subprocesstempfile.mkstemp


查看完整回答
反對 回復 2022-09-20
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號