Найти - Пользователи
Полная версия: Обработка исключений.
Начало » Python для новичков » Обработка исключений.
1 2
Gam
Прошу прощения.
Начал писать скрипт и не могу понять как обработать исключение при таймауте от 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
terabayt
https://docs.python.org/2/library/smtplib.html
а там сказано
https://docs.python.org/2/library/smtplib.html
timeout
Gam
except socket.timeout:
и
except socket.error:
всё равно ошибку вываливают.
terabayt
Gam
всё равно ошибку вываливают.
какую ошибку? покажите код
и почему вы думаете что оишбка должна быть в
email_logger.info("INS" + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file))))
?
Gam
Извиняюсь за 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
и почему вы думаете что оишбка должна быть в
email_logger.info("INS" + time.strftime("%d-%m-%Y",time.localtime(os.path.getmtime(file))))
?
На данный момент ip адрес из
handlers.SMTPHandler(('192.168.1.5', 25), FROM, TO, SUBJECT)
с моего рабочего места не доступен. В др. сети он полностью рабочий, но хочется прописать обработку исключения, что бы не было неприятных сюрпризов.
terabayt
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)
что выдаст?
Gam

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
terabayt
а так?
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)
Gam
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
2 вариант -
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
Gam
Как я понял, проблема из-за handlers.SMTPHandler, ибо на остальные ошибки исключения работают.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB