Python脚本手动执行正常,但通过cron时不行
我在两个树莓派上安装了OpenELEC。在其中一个树莓派上,我设置了一个Python脚本,它打开了一个网络连接并监听连接请求。下面的代码是另一个树莓派上运行的脚本,它连接到监听器并发送消息:
# Run the command on the local system to play the show
os.system(command)
# Set up network information for sending data and connect
r_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Open the client list file
clientlist = open("clients.txt", "r")
for line in clientlist.readlines():
try:
client = line.rstrip('\n').split(':')
r_socket.connect((client[0], int(client[1])))
except:
print("Failed to connect to remote device")
else:
# Hash IP and MAC addresses
hash = hashlib.sha224(r_socket.getsockname()[0] + " " + getHwAddr('eth0')).hexdigest()
# Send the message to other RPis on the network
r_socket.send(hash + "\n" + command)
# Close the socket when finished
r_socket.close()
最后,我在定时任务中设置了一个条目,让这个脚本在一天中的特定时间运行。脚本的前半部分能正常执行,但一到网络部分就出问题了。如果我手动运行这个脚本,它就能正常工作,把消息发送给监听的树莓派。
根据我的理解,树莓派上只有一个账户(root),这个脚本可以被所有用户运行(chmod a+x myscript.py)。所以,我觉得这不是权限的问题,但我就是搞不清楚到底是什么原因。
有没有人知道,为什么这个脚本的网络部分在定时任务中执行时会失败,而手动运行时却没问题呢?
1 个回答
2
你应该使用绝对路径来指定 clients.txt
和 command
。因为在 cron
执行程序的环境下,可能和你平常使用的命令行环境不一样(比如环境变量不同,工作目录也不同)。