wangyp

博客园 首页 联系 订阅 管理
模块:  
  
    定义:一堆代码实现了某个功能的代码集合。函数式编程完成一个功能,  
    示例:os 是操作系统的模块   
    分类:自定义模块/内置模块200个/开源模块 pypi.python.org  
    安装第三方模块:pip install/easy install/download package ---- python setup.py install/download  
    自定义模块:  
        __init__.py的目录就是自定义模块  
    好处:功能复用/解耦/可扩展性可维护性  
    调用方式:from #module name import function name  
  
内置模块:  
      
    time datetime模块  
      
        import time,datetime  
        print time.time() #1563521388.25  
        print time.ctime() #Fri Jul 19 15:29:48 2019  
        print time.gmtime() # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=19, tm_hour=7, tm_min=30, tm_sec=32, tm_wday=4, tm_yday=200, tm_isdst=0)  
        print time.localtime() #time.struct_time(tm_year=2019, tm_mon=7, tm_mday=19, tm_hour=15, tm_min=46, tm_sec=39, tm_wday=4, tm_yday=200, tm_isdst=0)  
        print time.mktime(time.localtime())  
        print time.strftime("%Y-%m-%d")  
        print time.strptime("2019-07-02","%Y-%m-%d")  
  
        print datetime.datetime.today() #2019-07-19 15:57:40.639000  
        print datetime.datetime.now() #2019-07-19 15:57:40.639000  
        print datetime.datetime.now().timetuple()  
  
    random模块  
      
        import  random  
        print random.random() #0.404556204712  
        print random.randint(1,100) #40  
        print random.randrange(1,200) #79  
  
        check_code = ""  
        for i in range(4):  
  
            currnet = random.randint(0,10)  
            check_code = check_code + str(currnet)  
        print check_code  
  
    os  
      
        # -*- coding:utf-8 -*-  
        import os  
        #这个模块主要是用来和OS进行交互的一堆混杂的方法在里面 更高级的模块还有shutil  
        #主要有os.path判断文件相关的东西  还可以os.system os.popen运行一些系统命令  
        print os.getcwd()  #获取当前的目录  
        os.system(r'cd d:\\')  #启动一个子shell 运行命令  
        print os.getcwd()   #所以不会有变化  
        os.chdir('d:\\')  
        print os.getcwd()  
        print os.curdir  # . 为什么是.呢  
        print os.pardir  # ..  
        print os.sep  # \  
        print os.stat('d:\\')  #查看目录或者文件的状态信息  
        os.mkdir(r'D:\\2')  #生成单级目录  
        os.rmdir(r'2')  
        os.makedirs('d:\\1\\2\\3')  
        os.removedirs(r'd:\1\2\3')  
        # print res  
        print os.listdir(os.getcwd())  
        os.rename('1','1.old')  
        print os.linesep  
        print os.environ  
        print os.path.split(os.getcwd())  
        print os.path.abspath('1.old') #绝对路径  
        print os.path.dirname('1.old') #  
        print os.path.basename('1.old') #文件名  
        print os.path.isabs('1.old')  
        print os.path.isdir('1.old')  
        print os.path.isfile('1.old')  
        print os.path.getctime('1.old')  #create time  
        print os.path.getatime('1.old') #access time  
        print os.path.getmtime('1.old') #modify time  
        res = os.popen('dir')  #可以取到返回值  
        res2 = os.system('dir') #只可以看到返回值的状态  
        print res.read()  
        print res2  
        import os  
        print os.stat('1.txt')  
      
    sys  
      
        # -*- coding:utf-8 -*-  
        import sys  
        #  这个模块主要是查看解释器相关的东西,比如运行的参数个数啊  最大的int大小啊 sys.exit 退出程序啊  
        print sys.path  #查找包的路径  
        print sys.argv  #参数  
          
    shutil  
      
        # -*- coding:utf-8 -*-  
        import  shutil  
        print dir(shutil)  
  
        f1 = open("1.txt")  
        f2 = open("2.txt",mode='w')  
        shutil.copyfileobj(f1,f2)  # 复制文件内容到2.txt  
  
        shutil.copyfile('1.txt','3.txt')  #直接文件名进行覆盖  
  
        shutil.copymode() #拷贝chmod可以改变的东西 777  
  
        shutil.copystat() #atime,mtime  
  
        shutil.copytree('/StoragePlus','/StoragePlus.bak')  #递归的拷贝  
        shutil.rmtree('/StoragePlus.bak') #递归的删除  
        shutil.make_archive("/",'gztar') #压缩文件 #tarfile zipfile用于解压  
  
  
  
    json/pickle/shelve  
      
        # -*- coding:utf-8 -*-  
        import  pickle,json,shelve  
  
        dict1 = dict(name='wyp',age='29')  
        # f = open('pickle.txt','w')  
        # pickle.dump(dict1,f) #Python对象序列化为一个字节流 从内存读取数据然后写入文件  
        f = open('pickle.txt','r')  
        dict2 = pickle.load(f) #从文件反序列存储的内容  json是所有语言通用的  只能序列化基本的数据类型  
        print dict2  
        #pickle是python独有的 可以序列化基本所有的数据类型  
  
  
        # d = shelve.open('shelve_test')  
  
        class Foo(object):  
            def __init__(self,n):  
                self.n = n  
        # f1 = Foo(1)  
        # f2 = Foo(2)  
        #  
        # d['test'] = ['1','2','3']  
        # d['t1'] = f1  
        # d['t2'] = f2  
        #  
        # d.close()  
        d = shelve.open('shelve_test')  
        print d.get('t1').n,d.get('t2').n,d.get('test')  
  
        #shelve 可以读取所有的key  而pickle只能挨次读取  
  
  
  
  
    xml:操作xml的  
      
        import  xml.etree.ElementTree as ET  
  
        tree = ET.parse("web.html")  
        root = tree.getroot()  
        print root.tag  
          
    PyYAML:操作yaml文件的  
      
        略  
          
    configParser:  
      
        用于生成和修改常见配置文档 回头实际应用吧  
      
    hashlib  
      
        MD5和SHA加密  
          
    subprocess  
      
        >>> subprocess.call('df -hT',shell=True)  
        文件系统              类型      容量  已用  可用 已用% 挂载点  
        /dev/mapper/rhel-root xfs        49G   17G   32G   35% /  
        devtmpfs              devtmpfs  3.9G     0  3.9G    0% /dev  
        tmpfs                 tmpfs     3.9G   80K  3.9G    1% /dev/shm  
        tmpfs                 tmpfs     3.9G  8.9M  3.9G    1% /run  
        tmpfs                 tmpfs     3.9G     0  3.9G    0% /sys/fs/cgroup  
        /dev/mapper/rhel-home xfs        24G   37M   24G    1% /home  
        /dev/sda1             xfs       497M  119M  379M   24% /boot  
        /dev/sr0              iso9660   4.0G  4.0G     0  100% /mnt  
        0  
          
        #Do not use stdout=PIPE or stderr=PIPE with this function as that can deadlock based on the child process output volume.   
        #Use Popen with the communicate() method when you need pipes.  
          
        >>> a = subprocess.Popen('df -hT',shell=True,stdout=subprocess.PIPE)      
        >>> a  
        <subprocess.Popen object at 0x7fabb64977d0>  
        >>> dir(a)  
        ['__class__', '__del__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_child_created', '_close_fds', '_communicate', '_communicate_with_poll', '_communicate_with_select', '_execute_child', '_get_handles', '_handle_exitstatus', '_internal_poll', '_set_cloexec_flag', '_translate_newlines', 'communicate', 'kill', 'pid', 'pipe_cloexec', 'poll', 'returncode', 'send_signal', 'stderr', 'stdin', 'stdout', 'terminate', 'universal_newlines', 'wait']  
        >>> a.stdout.read()  
        '\xe6\x96\x87\xe4\xbb\xb6\xe7\xb3\xbb\xe7\xbb\x9f              \xe7\xb1\xbb\xe5\x9e\x8b      \xe5\xae\xb9\xe9\x87\x8f  \xe5\xb7\xb2\xe7\x94\xa8  \xe5\x8f\xaf\xe7\x94\xa8 \xe5\xb7\xb2\xe7\x94\xa8% \xe6\x8c\x82\xe8\xbd\xbd\xe7\x82\xb9\n/dev/mapper/rhel-root xfs        49G   17G   32G   35% /\ndevtmpfs              devtmpfs  3.9G     0  3.9G    0% /dev\ntmpfs                 tmpfs     3.9G   80K  3.9G    1% /dev/shm\ntmpfs                 tmpfs     3.9G  8.9M  3.9G    1% /run\ntmpfs                 tmpfs     3.9G     0  3.9G    0% /sys/fs/cgroup\n/dev/mapper/rhel-home xfs        24G   37M   24G    1% /home\n/dev/sda1             xfs       497M  119M  379M   24% /boot\n/dev/sr0              iso9660   4.0G  4.0G     0  100% /mnt\n'  
        >>>   
      
    logging  
          
        import logging  
        logger = logging.getLogger("logger")  
  
        handler1 = logging.StreamHandler() #sys.stdout or sys.stderr  
        handler2 = logging.FileHandler(filename="test.log") # write to disk files  
  
        logger.setLevel(logging.DEBUG)  
        handler1.setLevel(logging.WARNING)  
        handler2.setLevel(logging.DEBUG)  
  
        formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")  
        handler1.setFormatter(formatter)  
        handler2.setFormatter(formatter)  
  
        logger.addHandler(handler1)  
        logger.addHandler(handler2)  
  
        # print handler1.level #30  
        # print handler2.level #10  
        # print logger.level   #10  
  
  
        logger.debug('This is a customer debug message')  
        logger.info('This is an customer info message')  
        logger.warning('This is a customer warning message')  
        logger.error('This is an customer error message')  
        logger.critical('This is a customer critical message')  
  
  
      
0719做什么:  
  
    把备份交换机程序分层  弄一个config目录出来   
  
      

  

posted on 2019-07-23 10:44  wangyp  阅读(142)  评论(0编辑  收藏  举报