You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Dark Sky Python API时遇'SyntaxError: await outside function'报错求助

Fixing the 'await' outside function SyntaxError with Dark Sky Python API

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_KEY with your actual Dark Sky API key.
  • Update latitude and longitude to your desired location coordinates.
  • Once you have the forecast object, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:18:33