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

树莓派Python天气脚本通过Crontab启动无数据输出问题排查

排查树莓派cron启动Python天气脚本无数据的问题

我来帮你梳理下这个问题——脚本在控制台跑没问题,cron启动后进程也在但就是没数据,大概率是路径、时区或者环境变量的锅,咱们一个个来排查:

1. 最可能的元凶:相对路径导致文件写去了奇怪的地方

你脚本里写的是with open('weatherdata.csv', 'a') as file:,用的是相对路径。当你在控制台运行脚本时,工作目录就是脚本所在的/home/pi/Documents/PythonProgramme/WeatherData/,所以csv乖乖生成在这里;但cron的默认工作目录是你的用户主目录(/home/pi),也就是说,脚本在cron下跑时,会把csv写到/home/pi/下面,而不是你预期的文件夹里!

解决起来很简单,把csv的路径改成绝对路径就行:

with open('/home/pi/Documents/PythonProgramme/WeatherData/weatherdata.csv', 'a') as file:

2. 检查cron的时区是否和你用的时区一致

schedule库是跟着系统时区走的,但cron的时区可能和你控制台用的不一样(比如默认是UTC)。举个例子:你设置的08:00是中欧时间,但cron用UTC的话,实际执行时间会是10:00(CET比UTC早2小时),你自然会以为任务没跑。

怎么验证?给脚本加个日志输出,然后把cron的输出定向到日志文件:

  • 先在脚本开头加一行打印时间的代码:
from datetime import datetime
print(f"脚本启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S %Z')}")
  • 然后修改crontab条目,把输出存起来:
@reboot python3 /home/pi/Documents/PythonProgramme/WeatherData/weatherdata.py >> /home/pi/weather_cron.log 2>&1 &

重启后过一会儿看看weather_cron.log里的时间是不是和你本地时间一致。如果不一致,就在crontab的最顶部加上时区设置:

TZ=Europe/Berlin

3. 确保cron能找到Python模块和正确的Python解释器

虽然进程在运行,但有可能cron的环境里找不到pyowm模块——比如你用了虚拟环境,或者pip装的模块不在cron的PATH里。

解决方法:

  • 先查一下你控制台用的Python3的绝对路径:
which python3

比如得到/usr/bin/python3,然后把crontab里的python3换成这个绝对路径:

@reboot /usr/bin/python3 /home/pi/Documents/PythonProgramme/WeatherData/weatherdata.py >> /home/pi/weather_cron.log 2>&1 &
  • 也可以在脚本里加个异常捕获,看看是不是模块导入出问题:
try:
    from pyowm import OWM
except ImportError as e:
    with open('/home/pi/weather_error.log', 'a') as f:
        f.write(f"{datetime.now()}: 导入pyowm失败: {str(e)}\n")
    raise

4. 最后检查下文件权限

如果你的weatherdata.csv已经在脚本目录存在,确认下pi用户有没有写入权限:

ls -l /home/pi/Documents/PythonProgramme/WeatherData/weatherdata.csv

要是权限不对,用chmod调整一下就行:

chmod u+w /home/pi/Documents/PythonProgramme/WeatherData/weatherdata.csv

一般来说,先改绝对路径就能解决问题,你可以先试试这个!

内容的提问来源于stack exchange,提问作者justuswolff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:07:38