Python脚本手动执行但不通过cron

标签 python linux xbmc

我在两个树莓派上安装了 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.txtcommand 使用绝对路径。 cron 执行环境很可能与您的 shell 环境不同(不同的环境变量,不同的工作目录)。

关于Python脚本手动执行但不通过cron,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22121584/

相关文章:

python - PyCharm 中 Python 控制台和终端的区别

python - 查询保存为 npz 的 NumPy 数组的 NumPy 数组很慢

linux - pids为什么会在容器中跳跃?

linux - 如何列出包含特定字符串的文件名

UPnP 检测延迟

bash - 在本地X session 中远程运行命令?

python - 如何将 defaultdict(list) 转换为 Pandas DataFrame

python - 根据包含空值的其他列使用掩码设置值

linux - 如何从目录中的文件名中保存多个 IP 地址?

javascript - 传递对 XBMC json-rpc 的引用以稍后识别答案