python脚本不会在启动时运行ubuntu

时间:2017-04-24 05:09:11

标签: python ubuntu mqtt paho

我尝试在启动时运行我的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

如果您需要更多信息,请与我们联系。

2 个答案:

答案 0 :(得分:0)

我自己也遇到过这个问题。对我来说,问题是路径。我可以使用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 &

如果适合你,请试试这个:)祝你好运。 虽然我没有将错误记录到文件中。

答案 1 :(得分:-1)

在我看来,你需要在你的python scrypt之前设置/更改文件的写权限:

f.write("it works " + t + "\n")

因为你工作是因为(也许你是文件的所有者)。

典型的linux文件权限描述为:

enter image description here

使用带有属性标志的 chmod ,所以 linux 也有权写入文件,请参考ubuntu help:)

相关问题