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

时间:2014-03-01 23:03:49

标签: python linux xbmc

我在两个Raspberry Pis上安装了OpenELEC。我在其中一个Pis上设置了一个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执行时失败,而不是在手动运行时失败?

1 个答案:

答案 0 :(得分:2)

您应该使用clients.txtcommand的绝对路径。 cron执行环境很可能与您的shell环境不同(不同的环境变量,不同的工作目录)。