zoukankan      html  css  js  c++  java
  • 对象支持上下文管理之with下的__enter__方法,和__exit__方法

    最先版本的

    from telnetlib import Telnet
    from sys import stdin, stdout
    from collections import deque
    
    class TelnetClient(object):
        def __init__(self, addr, port=23):
            self.addr = addr
            self.port = port
            self.tn = None
    
        def start(self):
            self.tn = Telnet(self.addr, self.port)
            self.history = deque()
    
            # 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)
    
    client = TelnetClient('127.0.0.1')
    
    print('
     start....')
    client.start()  # 启动clinet方法
    print('
     cleanup')
    client.cleanup()    # 退出,清理内存
    

    更新版本的

    from telnetlib import Telnet
    from sys import stdin, stdout
    from collections import deque
    
    class TelnetClient(object):
        def __init__(self, addr, port=23):
            self.addr = addr
            self.port = port
            self.tn = None
    
        def start(self):
            # self.tn = Telnet(self.addr, self.port)
            # self.history = deque()
            
            # 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)
            pass
    
        def __enter__(self):
            self.tn = Telnet(self.addr, self.port)
            self.history = deque()
            return self
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            self.tn.close()
            self.tn = None
            with open(self.addr + '_history.txt', 'w')as f:
                f.writelines(self.history)
    
    '''
    client = TelnetClient('127.0.0.1')
    print('
     start....')
    client.start()
    print('
     cleanup')
    client.cleanup()
    '''
    with TelnetClient('127.0.0.1') as client:
        client.start()
    

    with 监控 enter 和 __exit__方法:

    #_*_ encoding: utf-8 _*_   @author: ty  hery   2019/12/20
    
    
    打开文件对象
    f = open('03.txt','wb')
    # 2,向文件写入内容
    try:
        f.write(b'hello flask')
    except Exception:
        pass
    finally:
        # 3,关闭文件
        f.close()
    
    f = open('01.txt','wb') # 等同于下面的with open
    # with是上下文管理器,内部的代码全部都在with的监管之下运行的
    with open('03.txt','wb') as f:   # 在f对象中含有__enter__,和__exit__方法,with调用这些方法
        f.write(b'hello flask 01')
        f.write(b'hello flask 02')
        f.write(b'hello flask 03')
        f.write(b'hello flask 04')
        f.write(b'hello flask 05')
    
    class Foo(object):
        def __enter__(self):
            '''进入with语句的时候被with调用'''
            print('enter called')
    
        def __exit__(self,exc_type,exc_val,exc_tb):
            '''离开with语句的时候被with调用'''
            print('exit called')
            print('exc_type: %s' %exc_type)
            print('exc_val: %s' %exc_val)
            print('exc_tb: %s' %exc_tb)
    with Foo() as  foo:
        print('hello python ')
        a =1/0
        print('hello end')
    
    写入自己的博客中才能记得长久
  • 相关阅读:
    【整理】uclibc,eglibc,glibc之间的区别和联系
    C语言calloc()函数:分配内存空间并初始化——stm32中的应用
    收藏!了解UART总线工作原理看这一篇就够了!
    在stm32开发可以调用c标准库的排序和查找 qsort bsearch
    更少的直接百度,更多的取看API
    Sping中的IOC四种注解的简单记录
    使用for循环还是foreach循环?
    总是要还的
    EL表达式,保留小数点后两位
    如何遍历二叉树
  • 原文地址:https://www.cnblogs.com/heris/p/14113080.html
Copyright © 2011-2022 走看看