我尝试在启动时运行我的 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
如果您需要更多信息,请告诉我。
请您参考如下方法:
我自己也遇到过这个问题。对我来说,问题是路径。我可以通过使用 shell 脚本启动 python 脚本并从 crontab 启动 shell 脚本来让它工作。
这是我的 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 &
如果它对您有用,请尝试一下 :) 祝您好运。 不过,我还没有将错误记录到文件中。
