使用Dark Sky Python API时遇'SyntaxError: await outside function'报错求助
Hey there! Let's sort out that SyntaxError you're hitting. This is a super common gotcha when you're new to async Python—here's what's going on and how to fix it:
Why you're seeing this error
The await keyword can only be used inside a function defined with the async keyword. Right now, you're trying to call await darksky.get_forecast() directly at the top level of your script, which Python doesn't allow. Async functions depend on an event loop to handle asynchronous execution, so we need to structure your code to work with that.
How to fix your code
Wrap your forecast-fetching logic in an async function, then use Python's asyncio module to run that function. Here's your modified, working code:
import asyncio from darksky import DarkSky, languages, units, weather # Replace with your actual Dark Sky API key API_KEY = "your_unique_api_key_here" latitude = 40.7128 # Update with your target latitude longitude = -74.0060 # Update with your target longitude async def fetch_weather_forecast(): # Initialize the Dark Sky client darksky = DarkSky(API_KEY) # Fetch the forecast (now safely using await inside an async function!) 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 `[]` ) # Example: Print some data to confirm it works print(f"Current temp: {forecast.currently.temperature}°") print(f"Today's forecast: {forecast.hourly.summary}") # Run the async function via the event loop asyncio.run(fetch_weather_forecast())
For Python 3.6 or older
If you're using a Python version before 3.7, asyncio.run() isn't available. Use this code instead to run your async function:
loop = asyncio.get_event_loop() loop.run_until_complete(fetch_weather_forecast()) loop.close()
Quick reminders
- Don't forget to replace
API_KEYwith your actual Dark Sky API key. - Update
latitudeandlongitudeto your desired location coordinates. - Once you have the
forecastobject, you can access all the weather data fields documented in the Dark Sky API docs (the example prints a couple of values to get you started).
内容的提问来源于stack exchange,提问作者NameIsMarcus

