我尝试在启动时运行python脚本,但是它不起作用。

这是我的python脚本(不起作用):

#!/usr/bin/env python

import paho.mqtt.publish as publish
from datetime import datetime

t = str(datetime.now())
print t
with open("/home/james/mqtt/log.txt", "a+") as f:
    f.write("it works " + t + "\n")


这是我的python脚本(有效):

#!/usr/bin/env python

from datetime import datetime

t = str(datetime.now())
print t
with open("/home/james/mqtt/log.txt", "a+") as f:
    f.write("it works " + t + "\n")


这是我的rc.local文件(也可以尝试crontab并在/ect/init.d中设置服务):

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# /bin/mqtt_test.py &
# mosquitto_sub -t "mqtt"

/home/james/mqtt/script.sh
# /etc/mqtt/mqtt_test.py

exit 0


看起来通过导入paho.mqtt.publish可以使我的脚本停止运行,我是Linux的新手,我不知道为什么。有人可以帮我吗?谢谢你的帮助。

Ubuntu 16.04

让我知道您是否需要更多信息。

最佳答案

我自己已经遇到了这个问题。对我来说,问题在于道路。我可以通过使用外壳程序脚本启动python脚本并从crontab启动外壳程序脚本来使其工作。

这是我的launcher.sh。如果不想,则可以不使用sudo。 home/pi/record_data是我的文件所在的路径。

cd /
cd home/pi/record_data
sudo python record_video.py


在这种情况下,record_video.py是我要在启动时运行的python文件。在crontab编辑中,我在下面添加了这一行。

@reboot sh /home/pi/record_data/launcher.sh &


如果对您有用,请尝试一下:)祝您好运。
我还没有将错误记录到文件中工作。

09-04 09:27
查看更多