Форум сайта python.su
0
Добрый день, подскажите пожалуйста!
Скрипт питон3 работает 4-5 минут, потом перестает принимать данные с USB(COM) порта, после презапуска скрипта все норм, но на эти 4-5 минут, в винде в энергосбережение отключил временное отключение порта USB. Запуск от имени админа ничего не дает, но при этом на win 7х64 все работает без сучка, хотелось бы на вин 10 переехать…..
Офлайн
857
shiyriКакой скрипт?
Скрипт питон3 работает 4-5 минут, потом перестает принимать данные с USB(COM) порта
Офлайн
0
#! /usr/bin/python3 #coding: utf-8 import serial import MySQLdb import string import time import requests import cv2 import os import pysftp from time import gmtime, strftime s = serial.Serial('com5', 9600, bytesize=8, parity='N', stopbits=1, timeout=1) def photo(door): if door == 2: stream_url = 'http://192.168.2.74/action/snapshot/' elif door == 1: stream_url = 'http://192.168.2.74/action/snapshot/' absolute_script_dir = os.path.dirname(os.path.realpath(__file__)) save_dir = absolute_script_dir + '/snapshots/' save_path = save_dir + '/snapshot.jpg' cap = cv2.VideoCapture(stream_url) ret, frame = cap.read() cv2.imwrite(save_path, frame) try: with sftp.Connection('http://museum.ru/telegram2.php', username='123', password='3123') as sftp: remote = 'httpdocs/css/font/snapshot.jpg' local = 'D:\\www\\htdocs\\checkout\\snapshots\\snapshot.jpg' sftp.put(local,remote) sftp.close() except Exception: print("Ошибка ftp") while True: last = '' for byte in s.read(s.inWaiting()): last += chr(byte) if (len(last) == 14): conn = MySQLdb.connect('localhost', 'user', '123', 'sotr') cursor = conn.cursor() # Do whatever you want with last print (last) id = str(last)[4:] #print(id) try: in_out = int(str(last)[:-11]) except Exception: print("Ошибка в пропуске") else: zapros = ("SELECT COUNT(*) FROM fio_table where (propusk=" + id +")") zapros_korr = ("SELECT COUNT(*) FROM `prohod` WHERE propusk = " + id +" AND status = '00FF00' ") try: cursor.execute(zapros) except Exception: print("Ошибка в пропуске") else: row = cursor.fetchone() row = row[0] print(in_out) if row < 1: print("Доступ ЗАПРЕЩЕН") conn.close() if in_out == 931: photo(1) teleg = "ОХРАННИК РАЗБЛОКИРОВАЛ ТУРНИКЕТ!!!" #requests.get("http://museum.ru/telegram2.php?text='+ teleg'") response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg}) print("ОХРАННИК РАЗБЛОКИРОВАЛ ТУРНИКЕТ!!!") elif in_out == 962: photo(2) time.sleep(1) teleg = "ОХРАННИК ВПУСТИЛ НЕИЗВЕСТНОГО!!!" #requests.get("http://museum.ru/telegram2.php?text='+ teleg'") response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg}) print("ОХРАННИК ВПУСТИЛ НЕИЗВЕСТНОГО!!!") elif in_out == 972: photo(1) time.sleep(1) teleg = "ОХРАННИК ВЫПУСТИЛ НЕИЗВЕСТНОГО!!!" #requests.get("http://museum.ru/telegram2.php?text='+ teleg'") response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg}) print("ОХРАННИК ВЫПУСТИЛ НЕИЗВЕСТНОГО!!!") else: print("Доступ РАЗРЕШЕН") if in_out == 220: conn.close() time.sleep(1) print("Подключение к базе") conn = MySQLdb.connect(host='localhost', user='user', password='123', database='sotr', charset='utf8') cursor = conn.cursor() datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime()) datev = strftime("%H:%M:%S", time.localtime()) print("ОТправка запроса") cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', '00FF00', '" + datey + "', '" + datev + "')") cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'") rs = cursor.fetchall() ss = "" for o in range(len(rs)): ss+=str(rs) teleg = "" ss = ss[3:] ss = ss[:-5] print(ss) teleg = "Вошёл" + " "+ ss #requests.get("http://museum.ru/telegram2.php?text='+ teleg'") response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg}) conn.commit() conn.close() print("Запрос в базу на вход") if in_out == 200: print("Входит") cursor.execute(zapros_korr) row = cursor.fetchone() conn.close() photo(2) row = row[0] #if row > 0: # print("ИД уже на базе") тут нельзя войти 2 раза #else: print("Пропустить на вход") sss = str("2200" + id) ss = str.encode(sss) type(ss) # ensure it is byte representation print(ss) time.sleep(.5) s.write(ss) ss = " " elif in_out == 120: print("Запрос в базу на выход") conn.close() time.sleep(1) conn = MySQLdb.connect(host='localhost', user='user', password='123', database='sotr', charset='utf8') cursor = conn.cursor() datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime()) datev = strftime("%H:%M:%S", time.localtime()) cursor.execute("UPDATE prohod as pr, (SELECT id FROM prohod WHERE propusk='"+ id +"' ORDER BY id DESC LIMIT 1) as src SET pr.status = 'DC143C', pr.time_vih='" + datev + "', pr.date_vih = '" + datey + "', pr.time_ar=TIMEDIFF('" + datey + "', pr.data) WHERE pr.id = src.id;") cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'") rs = cursor.fetchall() ss = "" for o in range(len(rs)): ss+=str(rs) teleg = "" ss = ss[3:] ss = ss[:-5] print(ss) teleg = "Вышел" + " "+ ss #requests.get("http://museum.ru/telegram2.php?text='+ teleg'") response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg}) conn.commit() conn.close() elif in_out == 100: print("Выходит") cursor.execute(zapros_korr) row = cursor.fetchone() conn.close() photo(1) row = row[0] #if row < 1: # print("Еще не вошел") тут нельзя выйти 2 раза #else: print("Пропустить на выход") sss = str("1100" + id) ss = str.encode(sss) type(ss) # ensure it is byte representation print(ss) time.sleep(.5) s.write(ss) ss = " " elif in_out == 900: conn.close() time.sleep(1) conn = MySQLdb.connect(host='localhost', user='user', password='TWkuDB7jE84TLiqx', database='sotr', charset='utf8') cursor = conn.cursor() datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime()) datev = strftime("%H:%M:%S", time.localtime()) cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', '800080', '" + datey + "', '" + datev + "')") cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'") rs = cursor.fetchall() #iterate through rows ss = "" for o in range(len(rs)): ss+=str(rs) teleg = "" ss = ss[3:] ss = ss[:-5] print(ss) teleg = "ВНИМАНИЕ "+ ss + " НЕ ТРЕЗВЫЙ!!!" #requests.get("http://museum.ru/telegram2.php?text='+ teleg'") response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg}) conn.commit() conn.close() print("Бухой Ахтунг!!!") elif in_out == 910: conn.close() time.sleep(1) conn = MySQLdb.connect(host='localhost', user='user', password='TWkuDB7jE84TLiqx', database='sotr', charset='utf8') cursor = conn.cursor() datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime()) datev = strftime("%H:%M:%S", time.localtime()) cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', '800080', '" + datey + "', '" + datev + "')") cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'") rs = cursor.fetchall() #iterate through rows ss = "" for o in range(len(rs)): ss+=str(rs) teleg = "" ss = ss[3:] ss = ss[:-5] print(ss) teleg = ss + " отказывается пройти тест!!!" #requests.get("http://museum.ru/telegram2.php?text='+ teleg'") response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg}) conn.commit() conn.close() print("Отказался проходить тест!!!") elif in_out == 130: conn.close() time.sleep(1) conn = MySQLdb.connect(host='localhost', user='user', password='TWkuDB7jE84TLiqx', database='sotr', charset='utf8') cursor = conn.cursor() datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime()) datev = strftime("%H:%M:%S", time.localtime()) cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', 'FFFF00', '" + datey + "', '" + datev + "')") cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'") rs = cursor.fetchall() #iterate through rows ss = "" for o in range(len(rs)): ss+=str(rs) teleg = "" ss = ss[3:] ss = ss[:-5] print(ss) teleg = ss + " ПРОПУСТИЛ ПОСТОРОННЕГО!!!" response = requests.get(http://museum.ru/telegram2.php',params={'text': teleg}) conn.commit() conn.close() print("Пропустил шпиона!!!") elif in_out == 230: conn.close() time.sleep(1) conn = MySQLdb.connect(host='localhost', user='user', password='TWkuDB7jE84TLiqx', database='sotr', charset='utf8') cursor = conn.cursor() datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime()) datev = strftime("%H:%M:%S", time.localtime()) cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', 'FFFF00', '" + datey + "', '" + datev + "')") cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'") rs = cursor.fetchall() #iterate through rows ss = "" for o in range(len(rs)): ss+=str(rs) teleg = "" ss = ss[3:] ss = ss[:-5] print(ss) teleg = ss + " ВЫПУСТИЛ ПОСТОРОННЕГО!!!" #requests.get("http://museum.ru/telegram2.php?text='+ teleg'") response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg}) conn.commit() conn.close() print("Выпустил дисидента!!!")
Отредактировано shiyri (Март 15, 2020 13:26:34)
Офлайн
253
shiyriА как вы об этом судите?
потом перестает принимать данные с USB(COM) порта
logging...... s.is_open for byte in s.read(s.inWaiting()): last += chr(byte) logging...... len(last) if (len(last) == 14):
Отредактировано doza_and (Март 13, 2020 07:14:42)
Офлайн
857
shiyriПопробуй базу данных один раз открывать в начале работы скрипта и один раз закрывать в конце работы скрипта. Не факт, что в передаче данных дело.
Скрипт питон3 работает 4-5 минут, потом перестает
Офлайн
0
Да вы правы, mysql убрал и заработало без зависаний, то есть мне сейчас надо вывести ее в функцию? или в настройках базы данных что то поменять?
Отредактировано shiyri (Март 15, 2020 12:36:13)
Офлайн
0
Вынес запрос в отдельную функцию, не могу понять почему инициализация sftp не получается.
#! /usr/bin/python3 #coding: utf-8 import serial import MySQLdb import string import time import requests import cv2 import os import pysftp as sftp from time import gmtime, strftime s = serial.Serial('com4', 9600, bytesize=8, parity='N', stopbits=1, timeout=1) def photo(door): if door == 2: stream_url = 'http://192.168.2.74/action/snapshot/' elif door == 1: stream_url = 'http://192.168.2.74/action/snapshot/' absolute_script_dir = os.path.dirname(os.path.realpath(__file__)) save_dir = absolute_script_dir + '/snapshots/' save_path = save_dir + '/snapshot.jpg' cap = cv2.VideoCapture(stream_url) ret, frame = cap.read() cv2.imwrite(save_path, frame) def ftp_photo(): with sftp.Connection(host='server.ru',username='user',password='pass') as sftp: remote = 'httpdocs/css/font/snapshot.jpg' local = './snapshots/snapshot.jpg' sftp.put(local,remote) sftp.close() def telega(teleg): response = requests.get('museum.ru/css/font/telegram2.php',params={'text': teleg}) def sql(zapros): conn = MySQLdb.connect('localhost', 'user', 'TWkuDB7jE84TLiqx', 'sotr') cursor = conn.cursor() cursor.execute(zapros) global row row = cursor.fetchone() conn.commit() conn.close() return row while True: last = '' for byte in s.read(s.inWaiting()): last += chr(byte) if (len(last) == 14): print (last) id = str(last)[4:] print(id) try: in_out = int(str(last)[:-11]) except Exception: print("Ошибка в пропуске") else: zapros = "SELECT COUNT(*) FROM fio_table where (propusk=" + id +")" sql(zapros) row = row[0] print(in_out) if row < 1: print("Доступ ЗАПРЕЩЕН") photo(2) ftp_photo() telega("Тест из офиса")
Офлайн
294
ну дык оно вам пишет что нельзя так:
with sftp.Connection(host='server.ru',username='user',password='pass') as sftp:
with sftp.Connection(host='server.ru',username='user',password='pass') as conn:
[code python][/code]
Отредактировано PEHDOM (Март 15, 2020 20:03:18)
Офлайн
0
Помогите еще пожалста
отдельный кусок с сохраниением скрина с ип камеры работает, а в теле основного скрипта нет…. и ошибкон нет
def photo(door): if door == 2: stream_url = 'http://192.168.2.74/action/snapshot/' elif door == 1: stream_url = 'http://192.168.2.74/action/snapshot/' save_path0 = 'D:/www/htdocs/checkout/snapshots/snapshot.jpg' try: cap0 = cv2.VideoCapture(stream_url) ret, frame = cap0.read() cv2.imwrite(save_path0, frame) except Exception: print("Ошибка камеры")
Офлайн
857
shiyriДумаю, тебе код кто-то грамотный должен разработать. Все эти ошибки из-за общего уровня кода происходят. То есть ты думаешь, что данные не передаются, а на самом деле виснет база данных. Код написан в целом так, что это хороший и большой омут для ошибок. Вместо того чтобы его менять в том виде, в котором он есть, его нужно изначально грамотно продумать и написать, тогда и ошибки не будет ни одной.
то есть мне сейчас надо вывести ее в функцию? или в настройках базы данных что то поменять?
Офлайн