【问题标题】:Executing a python script including GPIO commands by cron in Raspberry Pi 2在 Raspberry Pi 2 中通过 cron 执行包含 GPIO 命令的 python 脚本
【发布时间】:2016-02-21 17:50:20
【问题描述】:

环境

  • 树莓派 2
  • raspbian-jessie-lite
  • Windows 8.1
  • 腻子 0.66 (SSH)

问题

无法让 cron 使用 sudo 执行 python 脚本。该脚本处理 GPIO 输入,因此应使用 sudo 调用它。该程序应该将温度和湿度保存到文件中,但 cat temp.txtcat humid.txt 给了我空字符串。

crontab

sudo crontab -e

* * * * * python /home/dixhom/Adafruit_Python_DHT/examples/temphumid.py 1>>/tmp/cronoutput.log 2>>/tmp/cronerror.log

python 脚本

#!/usr/bin/python

import sys
import Adafruit_DHT
import datetime

# Adafruit_DHT.DHT22 : device name
# 4 : pin number
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4)


if humidity is not None:
        f = open("humid.txt","w")
        str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), humidity)
        f.write(str)

else:
        print 'Failed to get reading. Try again!'
        sys.exit(1)

if temperature is not None:
        f = open("temp.txt","w")
        str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), temperature)
        f.write(str)
else:
        print 'Failed to get reading. Try again!'
        sys.exit(1)

cronerror.log 和 cronoutput.log

(空)

我尝试了什么

  • sudo crontab -e
  • /usr/bin/python 在 cron 中
  • chkconfig cron(cron 开启)
  • sudo apt-get update sudo apt-get upgrade
  • sudo reboot

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: python linux cron raspberry-pi2 gpio


    【解决方案1】:

    选项 1:您可以编辑 /etc/crontab。在那里,您可以指定哪个用户应在计划之后的列中执行相应的作业。

    选项 2:编辑 root 的 crontab 使用

    sudo su
    crontab -e
    

    我会选择第二个选项,因为这是 docs 建议的...

    (免责声明:对 GPIO 的东西不做任何保证。我只是假设您对“需要 sudo”是正确的,因为我从不在 raspi 上执行 GPIO。所以我提到了仅以 root 身份运行脚本。)

    【讨论】:

    • 谢谢。但是我尝试了这些,问题仍然存在。
    • 我假设脚本在交互调用时正在工作并产生输出。当它现在以 root 身份运行时,我认为它也会以 root 的主目录作为工作目录运行。由于脚本使用相对路径,您的文件将被放置在那里...
    • 没错……关键是相对路径。我找不到根的主目录,所以我修复了程序,以便将数据保存到绝对路径并且它有效!谢谢。
    • 我的荣幸。在这种情况下,请随意接受答案;)
    【解决方案2】:

    问题在于相对路径。数据被保存到与我所查看的不同的地方。

    变化

    f = open("humid.txt","w")
    

    f = open("/home/dixhom/Adafruit_Python_DHT/examples/humid.txt","w")
    

    解决问题。

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      相关资源
      最近更新 更多