我在两个树莓派上安装了 OpenELEC。我在其中一个树莓派上设置了一个 Python 脚本,它打开网络套接字并监听连接。以下代码来自在另一个 Raspberry Pi 上运行并连接到监听器以发送消息的脚本:
# 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()
最后,我有一个 crontab 条目可以在一天中的特定时间运行脚本。它正确执行脚本的前半部分,但一旦到达网络部分就会失败。如果我手动运行脚本,它会正常运行并将消息发送给监听器 Pi。
据我所知,Pi (root) 上只有一个帐户,所有用户都可以运行该脚本 (chmod a+x myscript.py)。所以,我不认为这是一个权限问题,但我无法弄清楚问题是什么。
有谁知道什么可能导致脚本的网络部分在由 cron 执行时失败,而在手动运行时却不会?
最佳答案
您应该为 clients.txt
和 command
使用绝对路径。 cron
执行环境很可能与您的 shell 环境不同(不同的环境变量,不同的工作目录)。
关于Python脚本手动执行但不通过cron,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22121584/