I' learning Python and I wonder if improving my code with a light debug level with if statement in my try/except bloc may be a good practice or if there is a better (or builtin) way to doing this.
#!/usr/bin/env python3
""" Testing conditions in try/except """
DEBUG_MODE = True
number = input("Type a integer: ")
try:
number = int(number)
except ValueError as except_detail:
if DEBUG_MODE:
print("ValueError: «{}»".format(except_detail))
else:
print("«{}» is not an integer".format(number))
else:
print("Your number {} is an integer".format(number))
I use a boolean, but a debug-level list()
work either for more than 2 levels.
Error reporting may also be improved with debug-level specific logging instructions.
You could use Python's logging
module for this, you can change the logging level
argument to record the level of logging detail you want:
import logging
logging.basicConfig(filename='log.txt', filemode='a', level=logging.DEBUG)
try:
number = int(number)
except ValueError as except_detail:
logging.warning("ValueError: «{}»".format(except_detail))
logging.info("«{}» is not an integer".format(number))
else:
logging.info("Your number {} is an integer".format(number))
标准库具有为此目的而设计的日志记录模块: https : //docs.python.org/2/library/logging.html内置了日志级别的调试,信息,警告,错误,严重
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.