Raspberry crontab python脚本

2024-04-26 01:35:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试在Rpi启动时启动一个python脚本,但是到目前为止,我所做的一切都没有成功。在

该脚本是此脚本的某些版本:https://www.raspberrypi.org/learning/temperature-log/worksheet/

#!/usr/bin/python
import os, sys
from subprocess import check_output
from re import findall
from time import sleep, strftime, time

def get_temp():
    temp = check_output(["vcgencmd","measure_temp"]).decode("UTF-8")
    temp = float(findall("\d+\.\d+",temp)[0])
    return(temp)

while True:
    log=open("cpu_temp.txt","a")
    temp = get_temp()
    log.write("{0} {1}".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp))+" degreeC\r\n")
    sleep(60)  
    log.close()

它自己工作得很好。我试着编辑crontab,有没有Python的绝对路径,以及编辑/etc/rc.本地在

我知道它不起作用,因为它应该每分钟创建一个文本文件并对其进行编辑,而不是在启动时创建的。我在crontab和rc.本地这是有效的。在

需要帮忙吗!在


Tags: fromimport脚本log编辑outputgettime
3条回答
sudo crontab -e

@reboot /usr/bin/python /path/to/file/script.py

/path/to/file/script.py可能是/home/username/script.py

如果它仍然不起作用,您可以尝试使用以下命令授予它执行权限:

^{pr2}$

您可以在~/.bashrc文件中调用脚本。它将在启动或终端打开时调用。在

写下:

python /path/to/your/script.py

在.bashrc文件的末尾。在

如果您的脚本位于/home/pi/tempcheck.py,那么您应该使用

sudo crontab -e

并附加行

^{pr2}$

然后保存并退出。在

更多详细信息请访问http://www.raspberrypi-spy.co.uk/2013/07/running-a-python-script-at-boot-using-cron/

你可以检查它是否正在运行

ps aux | grep tempcheck.py

注意,如果编辑root的crontab,python进程将作为root运行。因此,您应该在python脚本中使用绝对文件名:

log=open("/home/pi/cpu_temp.txt","a")

相关问题 更多 >