Форум сайта python.su
Прошу прощения.
Начал писать скрипт и не могу понять как обработать исключение при таймауте от SMTP-сервера.
try: email_logger.info("INS" + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file)))) except TimeoutError: logging.warning("Warning! SMTP server - TimeOut!")
Traceback (most recent call last): File "C:\Python27\lib\logging\handlers.py", line 929, in emit smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout) File "C:\Python27\lib\smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "C:\Python27\lib\smtplib.py", line 316, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python27\lib\smtplib.py", line 291, in _get_socket return socket.create_connection((host, port), timeout) File "C:\Python27\lib\socket.py", line 571, in create_connection raise err timeout: timed out
handler = handlers.SMTPHandler(('192.168.1.2', 25), FROM, TO, SUBJECT) email_logger = logging.getLogger('~@~.ru') email_logger.addHandler(handler) email_logger.setLevel = logging.info
Офлайн
https://docs.python.org/2/library/smtplib.html
а там сказано
https://docs.python.org/2/library/smtplib.htmltimeout
Отредактировано terabayt (Апрель 12, 2015 15:40:28)
Офлайн
except socket.timeout:
except socket.error:
Офлайн
Gamкакую ошибку? покажите код
всё равно ошибку вываливают.
email_logger.info("INS" + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file))))
Отредактировано terabayt (Апрель 12, 2015 15:49:44)
Офлайн
Извиняюсь за import ибо вырывал кусок из большого файла с кучей модулей.
import os, glob, zipfile, fileinput, shutil, time, logging, re, datetime, socket import dateutil.relativedelta from logging import handlers from lxml import etree LOG_FILENAME = 'G:\log_in.txt' FROM = '~@~.ru' TO = '~@~.ru' SUBJECT = 'INFO - Ins' logger = logging.getLogger('Logging') logger.setLevel(logging.DEBUG) logrotate = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=9000, backupCount=2) logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') handler = handlers.SMTPHandler(('192.168.1.5', 25), FROM, TO, SUBJECT) email_logger = logging.getLogger('~@~.ru') email_logger.addHandler(handler) email_logger.setLevel = logging.info dir_ins = "G:\\INS\\" os.chdir("G:/F/D") for file in glob.glob("*.zip"): if os.path.splitext(file)[0] == '630': if not os.path.exists(dir_ins): os.makedirs(dir_ins) try: email_logger.info("INS " + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file)))) except smtplib.SMTPConnectError: logging.warning("Warning! SMTP server - TimeOut!") logging.debug("INSURED " + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file))) + " - " + str(os.path.getsize(file))) shutil.move(os.path.abspath(file), dir_ins)
C:\Users\Gam\Desktop>TEST.py Traceback (most recent call last): File "C:\Python27\lib\logging\handlers.py", line 929, in emit smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout) File "C:\Python27\lib\smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "C:\Python27\lib\smtplib.py", line 316, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python27\lib\smtplib.py", line 291, in _get_socket return socket.create_connection((host, port), timeout) File "C:\Python27\lib\socket.py", line 571, in create_connection raise err timeout: timed out Logged from file TEST.py, line 24
terabaytНа данный момент ip адрес из
и почему вы думаете что оишбка должна быть в?email_logger.info("INS" + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file))))
handlers.SMTPHandler(('192.168.1.5', 25), FROM, TO, SUBJECT)
Офлайн
import os, glob, zipfile, fileinput, shutil, time, logging, re, datetime, socket import dateutil.relativedelta from logging import handlers from lxml import etree LOG_FILENAME = 'G:\log_in.txt' FROM = '~@~.ru' TO = '~@~.ru' SUBJECT = 'INFO - Ins' logger = logging.getLogger('Logging') logger.setLevel(logging.DEBUG) logrotate = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=9000, backupCount=2) logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') handler = handlers.SMTPHandler(('192.168.1.5', 25), FROM, TO, SUBJECT) email_logger = logging.getLogger('~@~.ru') email_logger.addHandler(handler) email_logger.setLevel = logging.info dir_ins = "G:\\INS\\" os.chdir("G:/F/D") for file in glob.glob("*.zip"): if os.path.splitext(file)[0] == '630': if not os.path.exists(dir_ins): os.makedirs(dir_ins) try: print("--- 1") email_logger.info("INS " + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file)))) print("--- 2") except socket.timeout: print("--- 3") logging.warning("Warning! SMTP server - TimeOut!") logging.debug("INSURED " + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file))) + " - " + str(os.path.getsize(file))) shutil.move(os.path.abspath(file), dir_ins)
Офлайн
terabayt
что выдаст?
C:\Users\Gam\Desktop>TEST.py --- 1 Traceback (most recent call last): File "C:\Python27\lib\logging\handlers.py", line 929, in emit smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout) File "C:\Python27\lib\smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "C:\Python27\lib\smtplib.py", line 316, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python27\lib\smtplib.py", line 291, in _get_socket return socket.create_connection((host, port), timeout) File "C:\Python27\lib\socket.py", line 571, in create_connection raise err timeout: timed out Logged from file TEST.py, line 24 --- 2
Офлайн
а так?
import os, glob, zipfile, fileinput, shutil, time, logging, re, datetime, socket, sys import dateutil.relativedelta from logging import handlers from lxml import etree LOG_FILENAME = 'G:\log_in.txt' FROM = '~@~.ru' TO = '~@~.ru' SUBJECT = 'INFO - Ins' logger = logging.getLogger('Logging') logger.setLevel(logging.DEBUG) logrotate = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=9000, backupCount=2) logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') handler = handlers.SMTPHandler(('192.168.1.5', 25), FROM, TO, SUBJECT) email_logger = logging.getLogger('~@~.ru') email_logger.addHandler(handler) email_logger.setLevel = logging.info dir_ins = "G:\\INS\\" os.chdir("G:/F/D") for file in glob.glob("*.zip"): if os.path.splitext(file)[0] == '630': if not os.path.exists(dir_ins): os.makedirs(dir_ins) try: email_logger.info("INS " + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file)))) except: print sys.exc_info() logging.warning("Warning! SMTP server - TimeOut!") logging.debug("INSURED " + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file))) + " - " + str(os.path.getsize(file))) shutil.move(os.path.abspath(file), dir_ins)
import os, glob, zipfile, fileinput, shutil, time, logging, re, datetime, socket import dateutil.relativedelta from logging import handlers from lxml import etree LOG_FILENAME = 'G:\log_in.txt' FROM = '~@~.ru' TO = '~@~.ru' SUBJECT = 'INFO - Ins' logger = logging.getLogger('Logging') logger.setLevel(logging.DEBUG) logrotate = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=9000, backupCount=2) logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') handler = handlers.SMTPHandler(('192.168.1.5', 25), FROM, TO, SUBJECT) email_logger = logging.getLogger('~@~.ru') email_logger.addHandler(handler) email_logger.setLevel = logging.info dir_ins = "G:\\INS\\" os.chdir("G:/F/D") for file in glob.glob("*.zip"): if os.path.splitext(file)[0] == '630': if not os.path.exists(dir_ins): os.makedirs(dir_ins) try: print("--- 1") email_logger.info("INS " + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file)))) print("--- 2") except Exception as e: print e logging.warning("Warning! SMTP server - TimeOut!") logging.debug("INSURED " + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file))) + " - " + str(os.path.getsize(file))) shutil.move(os.path.abspath(file), dir_ins)
Отредактировано terabayt (Апрель 12, 2015 17:21:05)
Офлайн
1 вариант -
C:\Users\Gam\Desktop>TEST.py Traceback (most recent call last): File "C:\Python27\lib\logging\handlers.py", line 929, in emit smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout) File "C:\Python27\lib\smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "C:\Python27\lib\smtplib.py", line 316, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python27\lib\smtplib.py", line 291, in _get_socket return socket.create_connection((host, port), timeout) File "C:\Python27\lib\socket.py", line 571, in create_connection raise err timeout: timed out Logged from file TEST.py, line 23
C:\Users\Gam\Desktop>TEST.py --- 1 Traceback (most recent call last): File "C:\Python27\lib\logging\handlers.py", line 929, in emit smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout) File "C:\Python27\lib\smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "C:\Python27\lib\smtplib.py", line 316, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python27\lib\smtplib.py", line 291, in _get_socket return socket.create_connection((host, port), timeout) File "C:\Python27\lib\socket.py", line 571, in create_connection raise err timeout: timed out Logged from file TEST.py, line 24 --- 2
Офлайн
Как я понял, проблема из-за handlers.SMTPHandler, ибо на остальные ошибки исключения работают.
Офлайн