Python 协程 BUG?

2017-02-10 00:35:19 +08:00
 qsnow6

参照aiohttp 官网的教程,写了个示例,发现语法报错。

import asyncio
import aiohttp
async with aiohttp.ClientSession() as session:
    async with session.get('https://api.github.com/events') as resp:
        print(resp.status)
        print(await resp.text())
-------------
  File "/Users/zed/PycharmProjects/example/used_aiohttp/1.py", line 3
    async with aiohttp.ClientSession() as session:
             ^
SyntaxError: invalid syntax

现在是不支持这样的写法了吗

async with xxxxx as xxxx:
    pass
2456 次点击
所在节点    Python
11 条回复
freestyle
2017-02-10 00:41:27 +08:00
得用 async def xxx(): 包起来
freestyle
2017-02-10 00:43:00 +08:00
qsnow6
2017-02-10 00:46:39 +08:00
@freestyle 包起来是可以的
但是看官网的示例是这么写的,还以为是我的姿势不对。。
qsnow6
2017-02-10 01:03:33 +08:00
qsnow6
2017-02-10 01:04:44 +08:00
![]( )
qsnow6
2017-02-10 01:06:06 +08:00
![]( )
?
qsnow6
2017-02-10 01:06:22 +08:00
![]( )
a87150
2017-02-10 01:52:52 +08:00
```
import asyncio
import aiohttp

async def fetch():
async with aiohttp.ClientSession() as session:
async with session.get('https://api.github.com/events') as r:
print(r.status)
print(await r.text())

loop = asyncio.get_event_loop()
loop.run_until_complete(fetch())
loop.close()
```
我估计官网是默认你会用 asyncio
a87150
2017-02-10 01:54:50 +08:00
原来回复不能用 markdown
LukeXuan
2017-02-10 10:19:42 +08:00
其实我觉得挺需要一个 apython 直接在 async def 环境内执行. py 文件
chy373180
2017-02-10 11:11:06 +08:00
要写在 async def 内

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/339447

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX