他の python スクリプトで使用するために、単純な telnetlib ベースの lib を作成しています。私はロギングクラスも使用しているため、1つの質問がありました.
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
ます。