Программа работает несколько часов нормально и падает
Есть программа, которая отправляет данные на сервер, считывает данные с него, считывает показания датчиков и отправляет команды исполнительным механизмам. В программе есть циклы-демоны, которые запускаются из main-файла(с GUI). Программа работает нормально насколько часов, но потом зависает или аварийно завершается. Что только не делал - ничего не помогло избавиться от этой проблемы. В частности я не понимаю почему в последнем листинге вылетели ошибки при погружении функции в сон и последующего ее запуска? Есть подозрение что где-то нужно поставить Except, но какие именно и где пока не вкурю, т.к. уже из головы пар валит. Если кому несложно, предложите пути решения и главное объясните, почему так происходит. P.s. Программа написана лично мной для личных целей(мини умный дом). Это не курсовая, дипломная или какая-то другая работа, да и я давно не студент. Изучаю питон для личного развития и хочу понять что я делаю не так. Код и листинг из PyCharm прилагаю.
Файл Stream_2.py
import gc
import threading
from time import sleep
import requests
import Variables
lock = threading.RLock()
def start1():
a=1
while a==1:
lock.acquire()
try:
r4_0 = Variables.parsing_GPIO_4relay1
r4_1 = str(r4_0[0])
r4_2 = str(r4_0[1])
r4_3 = str(r4_0[2])
r4_4 = str(r4_0[3])
params = {'params': str(Variables.parsing_ESP1),
'params1': str(Variables.Sadok_Light1),
'params2_1': r4_1,
'params2_2': r4_2,
'params2_3': r4_3,
'params2_4': r4_4, 'control': 'home'}
r = requests.get('http://f0555107.xsph.ru/index.php', params=params)
r.encoding = "UTF8"
print('start1 = Ok')
print(r.text)
# params.clear()
r.close()
break
except:
params = {'params': '0', 'params1': '0', 'params2_1': '0', 'params2_2': '0', 'params2_3': '0', 'params2_4': '0', 'control': 'home'}
r = requests.get('http://f0555107.xsph.ru/index.php', params=params)
r.encoding = "UTF8"
print('except start1' + r.text)
params.clear()
r.close()
sleep(5.0)
pass
finally:
lock.release()
gc.collect()
sleep(60.0)
start1()
def start2():
a = 1
while a == 1:
global lines
lock.acquire()
try:
url = "http://f0555107.xsph.ru/hello.html"
r = requests.get(url)
r.encoding = "UTF8"
print('start2 = Ok')
with open('response_server.html', 'w') as output_file:
output_file.write(r.text)
output_file.close()
with open('response_server.txt', 'w') as output_file:
output_file.write(r.text)
output_file.close()
text_file = open("response_server.html", "r")
lines = text_file.read().split(',')
print(lines)
# print(len(lines))
text_file.close()
Variables.receive_from_server = lines
Variables.receive_from_server1 = lines[0]
Variables.receive_from_server1 = lines[1]
Variables.receive_from_server1 = lines[2]
Variables.receive_from_server1 = lines[3]
Variables.receive_from_server1 = lines[4]
Variables.receive_from_server1 = lines[5]
Variables.receive_from_server1 = lines[6]
r.close()
break
except:
lines.append('0')
print('Except! start2')
sleep(5.0)
pass
finally:
lock.release()
gc.collect()
sleep(70.0)
start2()
def parsing_ESP():
global str3
a = 1
while a == 1:
lock.acquire()
try:
url = "http://192.168.0.110/sensors/adci1/"
r = requests.get(url)
r.encoding = "UTF8"
with open('test.html', 'w') as output_file:
output_file.write(r.text)
output_file.close()
with open('test1.txt', 'w') as output_file:
output_file.write(r.text)
output_file.close()
f = open('test1.txt')
str1=f.read()
f.close()
str2=str1[str1.find(";") + 1 : ]
str3=str2[str2.find(":") + 1 : str2.find(";")]
Variables.parsing_ESP = int(str3)
Variables.parsing_ESP1 = int(str3)
print('parsing_ESP = Ok')
r.close()
break
except:
print(' Except! parsing_ESP')
url= 'http://192.168.0.110/configrst?st=1'
r = requests.get(url)
str3=110
Variables.parsing_ESP = int(str3)
Variables.parsing_ESP1 = int(str3)
sleep(5.0)
r.close()
pass
finally:
lock.release()
gc.collect()
sleep(60.0)
parsing_ESP()
def parsing_GPIO_Sadok():
a = 1
while a == 1:
lock.acquire()
try:
url = "http://192.168.0.100/gpioprint"
r = requests.get(url)
Variables.status_code_sadok = r.status_code
r.encoding = "UTF8"
with open('sadok.html', 'w') as output_file:
output_file.write(r.text)
output_file.close()
with open('sadok1.txt', 'w') as output_file:
output_file.write(r.text)
output_file.close()
f = open('sadok1.txt')
str_sad = f.read()
# print(str_sad)
f.close()
str_sad2 = str_sad[:str_sad.find(";") + 1]
str_sad3 = str_sad2[str_sad2.find(":") + 1: str_sad2.find(";")]
Variables.Sadok_Light=str_sad3
Variables.Sadok_Light1 = str_sad3
print('parsing_GPIO_Sadok = Ok ')
r.close()
break
except:
print(' Except! parsing_GPIO_Sadok')
str_sad3=1
Variables.Sadok_Light = str_sad3
Variables.Sadok_Light1 = str_sad3
sleep(5.0)
pass
finally:
lock.release()
gc.collect()
sleep(30.0)
parsing_GPIO_Sadok()
def parsing_GPIO_4relay11():
a = 1
while a == 1:
lock.acquire()
try:
url = "http://192.168.0.120/gpioprint"
r = requests.get(url)
Variables.status_code_4relay = r.status_code
r.encoding = "UTF8"
with open('4relay.txt', 'w') as output_file:
output_file.write(r.text)
output_file.close()
f = open('4relay.txt')
str_4relay = f.read()
f.close()
print('parsing_GPIO_4relay = Ok')
str_4relay2 = str_4relay[str_4relay.find(":") + 1:]
r1 = str_4relay2[: str_4relay2.find(";")]
r2 = str_4relay[10:11]
r3 = str_4relay[18:19]
r4 = str_4relay[23:24]
relay_list = [r1, r2, r3, r4]
Variables.parsing_GPIO_4relay = relay_list
Variables.parsing_GPIO_4relay1 = relay_list
print('Variables.parsing_GPIO_4relay =' + str(Variables.parsing_GPIO_4relay))
r.close()
break
except:
r1 = '0'
r2 = '0'
r3 = '0'
r4 = '0'
relay_list = [r1, r2, r3, r4]
Variables.parsing_GPIO_4relay = relay_list
relay_list.clear()
print('Except! parsing_GPIO_4relay11')
sleep(5.0)
pass
finally:
lock.release()
gc.collect()
sleep(30.0)
parsing_GPIO_4relay11()
Файл logic_center.py
import gc
import threading
from threading import Thread
from time import sleep
import requests
import Variables
lock = threading.RLock()
def logicks_Sadok_Light():
a = 1
while a == 1:
lock.acquire()
try:
if int(Variables.parsing_ESP) <=100:
url= Variables.GPIO_sad_on
requests.get(url)
print('Night street')
else:
url = Variables.GPIO_sad_off
requests.get(url)
print('Day street!')
break
except:
print('Except! logics sadok light')
sleep(5.0)
pass
finally:
lock.release()
gc.collect()
def logicks_4relay_Light():
a = 1
while a == 1:
lock.acquire()
try:
if int(Variables.parsing_ESP) <= 100:
url = Variables.GPIO_4relay1_on
requests.get(url)
url = Variables.GPIO_4relay2_on
requests.get(url)
url = Variables.GPIO_4relay3_on
requests.get(url)
url = Variables.GPIO_4relay4_on
requests.get(url)
print('4Relay Night')
else:
url = Variables.GPIO_4relay1_off
requests.get(url)
url = Variables.GPIO_4relay2_off
requests.get(url)
url = Variables.GPIO_4relay3_off
requests.get(url)
url = Variables.GPIO_4relay4_off
requests.get(url)
print('4 Relay Day!')
break
except:
print('Except logics 4 relay!')
sleep(5.0)
pass
finally:
lock.release()
gc.collect()
def change_position_relay():
print(' написать change_position_relay()')
def remote_control_install():
a = 1
while a == 1:
lock.acquire()
try:
logicks_Sadok_Light()
logicks_4relay_Light()
break
except:
print('except! remote_control_install!')
sleep(5.0)
pass
finally:
lock.release()
gc.collect()
sleep(20.0)
remote_control_install()
Листинг в PyCharm
Получены новые вводные: данные датчика ESP - 14, 0, 1, 1, 1, 1, home
parsing_ESP = Ok
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
Night street
4Relay Night
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
start2 = Ok
['14', '0', '1', '1', '1', '1', 'home']
Night street
4Relay Night
Night street
4Relay Night
start1 = Ok
Получены новые вводные: данные датчика ESP - 13, 0, 1, 1, 1, 1, home
parsing_ESP = Ok
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
Night street
4Relay Night
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
check server 200
status_code Light_sensor_connection: 200
Night street
4Relay Night
start2 = Ok
['', '', '', '', '', '', '']
Night street
4Relay Night
start1 = Ok
Получены новые вводные: данные датчика ESP - 14, 0, 1, 1, 1, 1, home
parsing_ESP = Ok
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
Night street
4Relay Night
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
google.com 200
Night street
4Relay Night
start2 = Ok
['', '', '', '', '', '', '']
start1 = Ok
Получены новые вводные: данные датчика ESP - 13, 0, 1, 1, 1, 1, home
Night street
4Relay Night
Except! parsing_ESP
Exception in thread Thread-4:
Traceback (most recent call last):
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connection.py", line 169, in _new_conn
conn = connection.create_connection(
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\util\connection.py", line 96, in create_connection
raise err
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\util\connection.py", line 86, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] Попытка установить соединение была безуспешной, т.к. от другого компьютера за требуемое время не получен нужный отклик, или было разорвано уже установленное соединение из-за неверного отклика уже подключенного компьютера
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen
parsing_GPIO_Sadok = Ok
httplib_response = self._make_request(
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 394, in _make_request
conn.request(method, url, **httplib_request_kw)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connection.py", line 234, in request
super(HTTPConnection, self).request(method, url, body=body, headers=headers)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 1255, in request
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
self._send_request(method, url, body, headers, encode_chunked)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 1301, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 1250, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 1010, in _send_output
self.send(msg)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 950, in send
self.connect()
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connection.py", line 200, in connect
conn = self._new_conn()
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connection.py", line 181, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x000000000A54B2E0>: Failed to establish a new connection: [WinError 10060] Попытка установить соединение была безуспешной, т.к. от другого компьютера за требуемое время не получен нужный отклик, или было разорвано уже установленное соединение из-за неверного отклика уже подключенного компьютера
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\adapters.py", line 439, in send
resp = conn.urlopen(
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 755, in urlopen
retries = retries.increment(
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\util\retry.py", line 574, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='192.168.0.110', port=80): Max retries exceeded with url: /sensors/adci1/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000000000A54B2E0>: Failed to establish a new connection: [WinError 10060] Попытка установить соединение была безуспешной, т.к. от другого компьютера за требуемое время не получен нужный отклик, или было разорвано уже установленное соединение из-за неверного отклика уже подключенного компьютера'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 86, in parsing_ESP
r = requests.get(url)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='192.168.0.110', port=80): Max retries exceeded with url: /sensors/adci1/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000000000A54B2E0>: Failed to establish a new connection: [WinError 10060] Попытка установить соединение была безуспешной, т.к. от другого компьютера за требуемое время не получен нужный отклик, или было разорвано уже установленное соединение из-за неверного отклика уже подключенного компьютера'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 114, in parsing_ESP
parsing_ESP()
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 114, in parsing_ESP
parsing_ESP()
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 114, in parsing_ESP
parsing_ESP()
[Previous line repeated 326 more times]
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 106, in parsing_ESP
r.request.get(url)
UnboundLocalError: local variable 'r' referenced before assignment
Night street
4Relay Night
Night street
4Relay Night
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
Night street
4Relay Night
start1 = Ok
Получены новые вводные: данные датчика ESP - 13, 0, 1, 1, 1, 1, home
start2 = Ok
['13', '0', '1', '1', '1', '1', 'home']
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
Night street
4Relay Night
Получены новые вводные: данные датчика ESP - 13, 0, 1, 1, 1, 1, home
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
Night street
4Relay Night
start2 = Ok
['13', '0', '1', '1', '1', '1', 'home']
parsing_GPIO_Sadok = Ok
parsing_GPIO_4relay = Ok
Variables.parsing_GPIO_4relay =['1', '1', '1', '1']
Night street
4Relay Night
Fatal Python error: Cannot recover from stack overflow.
Python runtime state: initialized
Thread 0x00001268 (most recent call first):
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 188 in parsing_GPIO_4relay11
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 189 in parsing_GPIO_4relay11
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 189 in parsing_GPIO_4relay11
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 189 in parsing_GPIO_4relay11
...
Thread 0x00001474 (most recent call first):
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 148 in parsing_GPIO_Sadok
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 149 in parsing_GPIO_Sadok
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 149 in parsing_GPIO_Sadok
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 149 in parsing_GPIO_Sadok
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 149 in parsing_GPIO_Sadok
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 149 in parsing_GPIO_Sadok
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 149 in parsing_GPIO_Sadok
...
Thread 0x00001374 (most recent call first):
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 39 in start1
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 40 in start1
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 40 in start1
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 40 in start1
...
Thread 0x00000ba0 (most recent call first):
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 77 in start2
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 78 in start2
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 78 in start2
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 78 in start2
File "D:\Java work\eclipse\test\package1_copy\Stream_2.py", line 78 in start2
...
Current thread 0x00000ca4 (most recent call first):
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\utils.py", line 57 in _has_surrogates
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\_policybase.py", line 287 in _sanitize_header
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\_policybase.py", line 316 in header_fetch_parse
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\message.py", line 471 in get
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\message.py", line 578 in get_content_type
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\message.py", line 594 in get_content_maintype
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\feedparser.py", line 295 in _parsegen
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\feedparser.py", line 180 in _call_parse
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\feedparser.py", line 176 in feed
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\parser.py", line 56 in parse
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\email\parser.py", line 67 in parsestr
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 225 in parse_headers
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 331 in begin
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 1347 in getresponse
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 440 in _make_request
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 699 in urlopen
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\adapters.py", line 439 in send
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 655 in send
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 542 in request
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\api.py", line 61 in request
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\api.py", line 76 in get
File "D:\Java work\eclipse\test\package1_copy\logic_center.py", line 13 in logicks_Sadok_Light
File "D:\Java work\eclipse\test\package1_copy\logic_center.py", line 61 in remote_control_install
File "D:\Java work\eclipse\test\package1_copy\logic_center.py", line 70 in remote_control_install
...
Thread 0x000010f8 (most recent call first):
File "C:\Users\Noutbook\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1429 in mainloop
File "D:/Java work/eclipse/test/package1_copy/Lesson_3.py", line 437 in <module>