V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
qsnow6
V2EX  ›  Python

Python 协程 BUG?

  •  
  •   qsnow6 · 2017-02-10 00:35:19 +08:00 · 2406 次点击
    这是一个创建于 2639 天前的主题,其中的信息可能已经有所发展或是发生改变。

    参照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
    
    11 条回复    2017-02-10 11:11:06 +08:00
    freestyle
        1
    freestyle  
       2017-02-10 00:41:27 +08:00
    得用 async def xxx(): 包起来
    qsnow6
        3
    qsnow6  
    OP
       2017-02-10 00:46:39 +08:00
    @freestyle 包起来是可以的
    但是看官网的示例是这么写的,还以为是我的姿势不对。。
    qsnow6
        4
    qsnow6  
    OP
       2017-02-10 01:03:33 +08:00
    qsnow6
        5
    qsnow6  
    OP
       2017-02-10 01:04:44 +08:00
    ![]( )
    qsnow6
        6
    qsnow6  
    OP
       2017-02-10 01:06:06 +08:00
    ![]( )
    ?
    qsnow6
        7
    qsnow6  
    OP
       2017-02-10 01:06:22 +08:00
    ![]( )
    a87150
        8
    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
        9
    a87150  
       2017-02-10 01:54:50 +08:00
    原来回复不能用 markdown
    LukeXuan
        10
    LukeXuan  
       2017-02-10 10:19:42 +08:00 via Android
    其实我觉得挺需要一个 apython 直接在 async def 环境内执行. py 文件
    chy373180
        11
    chy373180  
       2017-02-10 11:11:06 +08:00
    要写在 async def 内
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2218 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 05:57 · PVG 13:57 · LAX 22:57 · JFK 01:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.