Python+Crontab的反应非常奇怪



这一次我再也不知道了。。。

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

/home/pi/beweasserung/beweaserungsBot.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')

正如你所看到的,脚本打印了";现在2文件有更多内容"转换为演示文件。到目前为止,这是有效的,但不和机器人还没有启动。。。

我希望有人能帮我做

很可能在树莓派建立互联网连接之前就已经执行了crontab。您可以启用和检查日志以进行验证。

克服这一问题的一个简单方法是,在执行bot.run之前,等待能够ping服务器

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")

最新更新