報錯 SyntaxError: 'async with' outside async function

Python使用aiohttp的時候報錯 SyntaxError: 'async with' outside async functionhtml

百度了一圈沒有找到答案,由於我是按照官網文檔打的,報錯了,頭大,還覺得是包被我改壞了session

圖片描述

結果,回看之前的代碼,發現是由於,這個async with xxx as xxx:這個結構必須放在async def xxx():這樣子的函數裏面才行。async

上代碼ide

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(url, timeout=5) as resp:
            print(await resp.text())

完整代碼(作了一個嵌套)函數

import aiohttp
import asyncio
import time

url = 'http://docs.aiohttp.org/en/stable/client_quickstart.html'

async def getapge(session, url):
    async with session.get(url,timeout=5) as resp:
        print(await resp.text())

async def main():
    async with aiohttp.ClientSession() as session:
        await getapge(session, url)

#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
start = time.time()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

end = time.time()
#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

print('spend time is {}'.format(end - start))

OK,問題解決oop

最後給大家看下我優美的桌面ui

圖片描述

我想順便分享一下我選購顯示器的經驗url

6月1號那天在京東買了一個AOC的顯示器spa

圖片描述

就是這款,算了一下PPI,123,我以爲很棒,足夠細膩,大小又剛剛合適(寢室的桌子不是很大),很是滿意,幸福感慢慢code

之前用的筆記本是美帝聯想的R720,屏幕是一塊45%ntsc色域的15.6屏幕,如今回看真的辣眼睛,窄邊框和色域真的過重要了

相關文章
相關標籤/搜索