我正在编写基于 telnetlib 的简单库,供其他 python 脚本使用。我也在使用日志记录类,因此我有一个问题:有可能吗,做这样的事情是否是好的 python 实践:
def printd(args):
""" debug on stdout """
sys.stdout.write(time.strftime("%H:%M:%S ") + args.rstrip() + '\n')
def printe(args):
""" error on stderr """
sys.stderr.write(time.strftime("%H:%M:%S ") + args.rstrip() + '\n')
class Connections:
""" Telnet lib connection wrapper """
def __init__(self, host, port, timeout, logger):
""" if external logger is passed - all msgs will be passed to it,
otherwise will use printd and printe functions """
self.timeout = timeout
self.host = host
self.port = port
self.connections = {}
try:
res = isinstance(logger, logging.Logger)
except TypeError:
res = False
except:
res = False
if res == True:
self.log = logger
self.log_debug = self.log.debug
self.log_info = self.log.info
self.log_error = self.log.error
else:
self.log_debug = printd
self.log_error = printe
def connect2(self, helloMsg):
try:
self.c = telnetlib.Telnet(self.host, self.port)
except socekt.error:
self.c = None
self.log_error("Could not connect to %s:%d" % (self.host, self.port))
except IOError:
self.log_error("Could not connect to %s:%d" % (self.host, self.port))
self.c = None
在构造函数中我传递记录器,如果存在,我想使用它的日志方法来打印消息,如果没有,我想使用printd
和printe
函数。