我在Pi上运行一个Python脚本,该脚本每分钟向我的LCN主服务器发送一次POST数据请求,其中一个PHP文件将数据存储到数据库中。在一天的大部分时间里,一切正常,但到了晚上,程序崩溃,并且最大重试次数超过了。我希望这大约是午夜,因为我总是在午夜的FTP连接上遇到LCN问题。
是否可以继续重试或断开连接,然后重新连接并重试。
我的Python脚本在下面。
while 1:
second = dt.now().second
min = dt.now().minute
hour = dt.now().hour
if (hour == 00) and (min == 00) and (second < 5):
totalTemp = []
average = 0
if (second == 0):
CurrentTemp = readTemp(probeTemp)
print ("current temp : %s" % CurrentTemp)
totalTemp.append(CurrentTemp)
average = round(sum(totalTemp) / len(totalTemp), 1)
print ("average temp: %s" % average)
myobj = {'curentTemp': CurrentTemp, 'averageTemp': average}
x = requests.post(url, data = myobj)
time.sleep(3)
这是我在终端中遇到的完整错误
Traceback (most recent call last):
File "homeTemp.py", line 37, in <module>
x = requests.post(url, data = myobj)
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 116, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='dansonrunners.uk', port=80): Max retries exceeded with url: /weatherStation/insertDB.php (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x75d7ec10>: Failed to establish a new connection: [Errno 110] Connection timed out',))
答案 0 :(得分:0)
您可以使用try-except包围requestpart,以防止python脚本崩溃,如下所示
try:
x = requests.post(url, data = myobj)
except(Exception as e):
# can replaced with an detailed exception like requests.exceptions.*
print(e)