Python 如何让对象支持上下文管理

Jackey Python 747 次浏览 没有评论
# 如何让对象支持上下文管理
from telnetlib import Telnet
from collections import deque
from sys import stdout, stdin


class TelnetClient(object):
    def __init__(self, addr, port=23):
        self.history = deque()
        self.addr = addr
        self.port = port
        self.tn = None

    def start(self):
        # user
        t = self.tn.read_until('login: ')
        stdout.write(t)
        user = stdin.readline()
        self.tn.write(user)

        # password
        t = self.tn.read_until('Password: ')
        if t.startswith(user[:-1]): t = t[len(user) + 1:]
        stdout.write(t)
        self.tn.write(stdin.readline())

        t = self.tn.read_until('$ ')
        stdout.write(t)
        while True:
            uinput = stdin.readline()
            if not uinput:
                break
            self.history.append(uinput)
            self.tn.write(uinput)
            t = self.tn.read_until('$ ')
            stdout.write(t[len(uinput) + 1:])

    def cleanup(self):
        self.tn.close()
        self.tn = None
        with open(self.addr + '_history.txt', 'w') as f:
            f.writelines(self.history)

# 使用上下文管理协议
    def __enter__(self):
        self.tn = Telnet(self.addr, self.port)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cleanup()


with TelnetClient('127.0.0.1') as client:
    client.start()
'''
client = TelnetClient('127.0.0.1')
print('\nstart...')
client.start()
print('\ncleanup')
client.cleanup()
'''

 

发表评论

您的电子邮箱地址不会被公开。

Go