Python + Crontab 反应很奇怪

Python + Crontab reacts pretty weird

又是那个我不知道的时候了...

我有一个 cronjob 是: @reboot root /usr/bin/python3 /home/pi/bewaesserung/bewaesserungsBot.py >> /home/pi/bewaesserung/log.txt &

/home/pi/bewaesserung/bewaesserungsBot.py文件内容为:

#!/usr/bin/python3

import discord
from discord.ext import commands
import sys
import os
import socket
from datetime import datetime


bot = commands.Bot(command_prefix='!')
ip = 'X.X.X.X'
port = XXXX


f = open("demofile2.txt", "a")
f.write("Now2 the file has more content!")
f.close()


@bot.event
async def on_message(msg):
        if(msg.author == bot.user):
                return

        print(datetime.now().strftime("%m/%d/%Y, %H:%M:%S") + ' new received Message: ' + msg.content)

        try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect((ip, port))
                s.settimeout(20)
                msgToSend = 'do:' + msg.content
                s.send(msgToSend.encode('utf-8'))
                rcv = s.recv(1024).decode()
                print(datetime.now().strftime("%m/%d/%Y, %H:%M:%S") + ' send Back:' + rcv)
                if(rcv):
                          await msg.channel.send(rcv)
        except:
                await msg.channel.send('Timeout!')
                print('Timeout!')

        s.close()


bot.run('NOPE')

如您所见,脚本打印“Now2 the file has more content!”到演示文件中。 到目前为止,这是有效的,但 discord 机器人没有启动...

我希望有人能帮助我

很可能 crontab 在 raspberry pi 甚至建立互联网连接之前就开始执行。您可以启用并检查日志来验证。

克服此问题的一种简单方法是等到您能够 ping 服务器后再执行 bot.run

import os
import time

def wait_for_network():
    while os.system("ping -c 1 8.8.8.8") != 0:
        time.sleep(1)
        continue
    return

if __name__ == "__main__":
    wait_for_network()
    bot.run("NOPE")