Python 3.5:“与...同步”导致SyntaxError。为什么? [英] Python 3.5: "async with" results in SyntaxError. Why?

查看:129
本文介绍了Python 3.5:“与...同步”导致SyntaxError。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 3.5,根据 PEP 492 可以使用语法来访问异步,但是当我尝试使用它时却出现了SyntaxError。我在做什么错?

I am using Python 3.5, which, according to PEP 492 should have access to the async with syntax, yet I get a SyntaxError when I try to use it. What am I doing wrong?

In [14]: sys.version
Out[14]: '3.5.2 (default, Oct 11 2016, 04:59:56) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)]'

In [15]: async with aiohttp.ClientSession() as session:
  File "<ipython-input-15-9799c5ce74cf>", line 1
    async with aiohttp.ClientSession() as session:
             ^
SyntaxError: invalid syntax


推荐答案

您不能使用具有的异步功能,而没有 async 功能。正如文档所说的

You can not use async with without async function. As the docs say:


在异步def函数外部使用异步是一个SyntaxError。

It is a SyntaxError to use async with outside of an async def function.

但是此代码将起作用:

async def some_function():
    async with aiohttp.ClientSession() as session:
        pass

或查看文档

这篇关于Python 3.5:“与...同步”导致SyntaxError。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆