我想在沒有 Web 服務器的情況下從本地主機異步獲取文件。似乎可以使用 file:// 方案。以下代碼示例取自文檔,但顯然它不起作用:import aiohttpimport asyncioasync def fetch(session, url): async with session.get(url) as response: return await response.text()async def main(): async with aiohttp.ClientSession() as session: html = await fetch(session, 'file://localhost/Users/user/test.txt') print(html)if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main())如何讓它工作?我看到的一種方法是使用 run_in_executor 在單獨的線程池中使用“curl file://path”,但我認為應該有一種方法可以修復代碼
1 回答

犯罪嫌疑人X
TA貢獻2080條經驗 獲得超4個贊
如果需要獲取本地文件的內容,可以使用普通的 Python 內置來完成,例如:
with open('Users/user/test.txt') as rd:
html = rd.read()
如果文件不是很大,并且存儲在本地文件系統上,您甚至不需要使其異步,因為讀取它的速度足夠快,不會干擾事件循環。如果文件很大或由于其他原因讀取速度可能很慢,則應通讀它以防止它阻止其他 asyncio 代碼。例如(未經測試):run_in_executor
def read_file_sync(file_name):
with open('Users/user/test.txt') as rd:
return rd.read()
async def read_file(file_name):
loop = asyncio.get_event_loop()
html = await loop.run_in_executor(None, read_file_sync, file_name)
return html
添加回答
舉報
0/150
提交
取消