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

树莓派传感器脚本Thonny运行正常,加入crontab后无法写入data.json

树莓派DHT11脚本crontab运行无法写入data.json的解决办法

核心问题分析

脚本在Thonny中运行正常,但通过crontab执行时无法写入data.json,主要由路径不匹配、环境变量差异、代码变量作用域错误这几个原因导致,以下是针对性的解决步骤:

1. 替换相对路径为绝对路径

Thonny运行脚本时,工作目录默认是脚本所在文件夹;但crontab的默认工作目录是用户家目录(如/home/pi),脚本中使用的data.json相对路径会指向家目录,而非脚本所在位置,导致找不到文件或写入到错误位置。

修改脚本:
在开头添加获取脚本绝对路径的代码:

# 在import os之后添加
script_dir = os.path.dirname(os.path.abspath(__file__))
data_file_path = os.path.join(script_dir, 'data.json')

然后将所有涉及data.json的文件操作替换为data_file_path,例如:

  • getExistingData函数:
    def getExistingData():
        global dataList
        with open(data_file_path) as fp:
            dataList = json.load(fp)
        print(dataList)
    
  • startupCheck函数中的文件操作:
    # 检查文件存在性
    if os.path.isfile(data_file_path) and os.access(data_file_path, os.R_OK):
        ...
    # 创建文件
    with open(data_file_path, "w") as f:
        ...
    
  • 写入数据的代码:
    with open(data_file_path, "w") as f:
        json.dump(dataList, f, indent=4, separators=(',',': '))
    

2. 修复全局变量作用域问题

原代码中getExistingData函数里的dataList是局部变量,读取的现有数据不会同步到全局的dataList,导致写入时会覆盖之前的数据(或写入空列表)。

在getExistingData函数开头添加global dataList声明,确保使用全局变量:

def getExistingData():
    global dataList
    with open(data_file_path) as fp:
        dataList = json.load(fp)
    print(dataList)

3. 指定crontab中的Python绝对路径

crontab默认使用系统全局Python环境,可能和Thonny使用的Python版本(或虚拟环境)不一致,导致依赖库(如adafruit_dht、gpiozero)找不到。

首先获取Thonny使用的Python路径:打开Thonny,在菜单栏点击运行→配置解释器查看路径,或在终端执行:

which python3

假设得到路径为/usr/bin/python3,则crontab条目应写为:

# 示例:每分钟执行一次脚本,并输出日志到log文件
* * * * * /usr/bin/python3 /home/pi/your_script_folder/your_script.py >> /home/pi/dht_script_log.log 2>&1
  • 替换/home/pi/your_script_folder/your_script.py为脚本的绝对路径
  • >> /home/pi/dht_script_log.log 2>&1用于记录脚本输出和错误,方便排查问题

4. 检查并设置文件权限

确保脚本所在目录和data.json文件拥有当前用户的读写权限:

# 给脚本所在目录添加读写执行权限
chmod u+rwx /home/pi/your_script_folder/
# 给data.json添加读写权限
chmod u+rw /home/pi/your_script_folder/data.json

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:09:19