简体   繁体   中英

SyntaxError: 'await' outside function

Hello I am new to python and am trying to work with a Dark Sky python API made by Detrous. When I run the demo code I am presented with an error:

forecast = await darksky.get_forecast(
              ^
SyntaxError: 'await' outside function

this error results from:

forecast = await darksky.get_forecast(
    latitude, longitude,
    extend=False, # default `False`
    lang=languages.ENGLISH, # default `ENGLISH`
    units=units.AUTO, # default `auto`
    exclude=[weather.MINUTELY, weather.ALERTS] # default `[]`
)

I am not too sure how to resolve this issue and am using python 3.

Thanks

I think this answer will be useful for people who search the same question as me. To use async functions in synchronous context you can use event loop. You can write it from scratch for education purposes. You can start from this answer https://stackoverflow.com/a/51116910/14154287 And continue education with David Beazley books.

But developers of asyncio already did this for you.

import asyncio

loop = asyncio.get_event_loop()
forecast = loop.run_until_complete(darksky.get_forecast(...<here place arguments>...))
loop.close()

The await keyword can be used only in asynchronous functions and methods. You can read more on asynchronous code to understand why.

The solution, without having any details about what you want to accomplish and how, is to use darksky = DarkSky(API_KEY) instead of darksky = DarkSkyAsync(API_KEY) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM