zoukankan      html  css  js  c++  java
  • python学习day-9 常用模块与包

    import os
    def file_handler(backend_data,res=None,type='fetch'):
        if type == 'fetch':
            with open('haproxy.conf','r') as read_f:
                tag=False
                ret=[]
                for read_line in read_f:
                    if read_line.strip() == backend_data:
                        tag=True
                        continue
                    if tag and read_line.startswith('backend'):
                            # tag=False
                            break
                    if tag:
                        print('33[1;45m%s33[0m' %read_line,end='')
                        ret.append(read_line)
            return ret
        elif type == 'change':
            with open('haproxy.conf', 'r') as read_f, 
                    open('haproxy.conf_new', 'w') as write_f:
                tag = False
                has_write = False
                for read_line in read_f:  # server
                    if read_line.strip() == backend_data:
                        tag = True
                        continue
                    if tag and read_line.startswith('backend'):
                        tag = False
                    if not tag:
                        write_f.write(read_line)
                    else:
                        if not has_write:
                            for record in res:
                                write_f.write(record)
                            has_write = True
            os.rename('haproxy.conf', 'haproxy.conf.bak')
            os.rename('haproxy.conf_new', 'haproxy.conf')
            os.remove('haproxy.conf.bak')
    
    def fetch(data):
        # print('33[1;43m这是查询功能33[0m')
        # print('33[1;43m用户数据是33[0m',data)
        backend_data='backend %s' %data
        return file_handler(backend_data)
    
    
    
    def add():
        pass
    
    def change(data):
        # print('这是修改功能')
        # print('用户输入的数据是',data)
        backend=data[0]['backend'] #文件当中的一条记录 www.oldboy1.org
        backend_data='backend %s' %backend #backend www.oldboy1.org
        #       server 2.2.2.4 2.2.2.4 weight 20 maxconn 3000
    
        old_server_record='%sserver %s %s weight %s maxconn %s
    ' %(' '*8,data[0]['record']['server'],
                                                                  data[0]['record']['server'],
                                                                  data[0]['record']['weight'],
                                                                  data[0]['record']['maxconn'])
    
        new_server_record = '%sserver %s %s weight %s maxconn %s
    ' % (' ' * 8, data[1]['record']['server'],
                                                                     data[1]['record']['server'],
                                                                     data[1]['record']['weight'],
                                                                     data[1]['record']['maxconn'])
        print('用户想要修改的记录是',old_server_record)
        res=fetch(backend) #fetch('www.oldboy1.org')
        print('来自change函数--》',res)
        if not res or old_server_record not in res:
            return '你要修改的记录不存在'
        else:
            index=res.index(old_server_record)
            res[index]=new_server_record
    
        res.insert(0,'%s
    ' %backend_data)
        file_handler(backend_data,res=res,type='change')
    
    
    def delete():
        pass
    
    if __name__ == '__main__':
        msg='''
        1:查询
        2:添加
        3:修改
        4:删除
        5:退出
        '''
        msg_dic={
            '1':fetch,
            '2':add,
            '3':change,
            '4':delete,
        }
    
        while True:
            print(msg)
            choice=input('请输入你的选项:').strip()
            if not choice:continue
            if choice == '5':break
    
            data=input('请输入你的数据:').strip()
    
            if choice != '1':
                data=eval(data)
    
            res=msg_dic[choice](data)
            print('最终结果是--》',res)
    # [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}}]
    View Code

    查询修改操作代码、tag的用法

    1.在python文件写一些不会运行的函数模块等,要运行的代码写在   if _name_==‘_main_ ’下边  这是一种规范

    2.交换

    3.解压

     4.os

    os.remove("a.txt","b.txt")

    6._name_有两种用法

    1.当文件被调用,并没有被执行时   _name_!=_main_          _name_等于模块名

      当文件当作脚本执行时,_name_=_main_

      可以用if(_name_=="_main_")    用于被调用文件的测试

    5.文件操作

    with open('haproxy.conf', 'r') as read_f,
         open('haproxy.conf_new', 'w') as write_f:

    ------------------------------------------------------------------------------------------------------------------

    http://www.cnblogs.com/linhaifeng/articles/6379069.html#_label1

    一、模块

    1.一个模块就是一个包含了一组功能的python文件,比如spam.py,模块名为spam,可以通过import spam使用。
    模块可以分为四个通用类别:
       1 使用python编写的.py文件
      2 已被编译为共享库或DLL的C或C++扩展
      3 把一系列模块组织到一起的文件夹(注:文件夹下有一个__init__.py文件,该文件夹称之为包)
      4 使用C编写并链接到python解释器的内置模块
    2.优点
    1、从文件级别组织程序,更方便管理
    随着程序的发展,功能越来越多,为了方便管理,我们通常将程序分成一个个的文件,这样做程序的结构更清晰,方便管理。这时我们不仅仅可以把这些文件当做脚本去执行,还可以把他们当做模块来导入到其他的模块中,实现了功能的重复利用
    
    2、拿来主义,提升开发效率
    同样的原理,我们也可以下载别人写好的模块然后导入到自己的项目中使用,这种拿来主义,可以极大地提升我们的开发效率
    3.调用模块的方式
    import spam
    import sys,os,re 一行引入多个模块

    from spam import read1,read2


    二、包
    1.包就是一个包含有__init__.py文件的文件夹,所以其实我们创建包的目的就是为了用文件夹将文件/模块组织起来
    
    需要强调的是:
      1. 在python3中,即使包下没有__init__.py文件,import 包仍然不会报错,而在python2中,包下一定要有该文件,否则import 包报错
    
      2. 创建包的目的不是为了运行,而是被导入使用,记住,包只是模块的一种形式而已,包的本质就是一种模块
    2.包的调用
    import glance.db.models
    from glance.db import models


    3.常用模块

    ①时间模块

    在Python中,通常有这几种方式来表示时间:

    
    
    • 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
    • 格式化的时间字符串(Format String)
    • 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)
     1 --------------------------转换时间
     2 # localtime([secs])
     3 # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
     4 time.localtime()
     5 time.localtime(1473525444.037215)
     6 
     7 # gmtime([secs]) 和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。
     8 
     9 # mktime(t) : 将一个struct_time转化为时间戳。
    10 print(time.mktime(time.localtime()))#1473525749.0
    11 
    12 
    13 # strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
    14 # time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
    15 # 元素越界,ValueError的错误将会被抛出。
    16 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56
    17 
    18 # time.strptime(string[, format])
    19 # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
    20 print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
    21 #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
    22 #  tm_wday=3, tm_yday=125, tm_isdst=-1)
    23 #在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。

    ② random模块
    
    
    import random  
     print(random.random())#(0,1)----float    大于0且小于1之间的小数 
     print(random.randint(1,3))  #[1,3]    大于等于1且小于等于3之间的整数  
     print(random.randrange(1,3)) #[1,3)    大于等于1且小于3之间的整数 
     print(random.choice([1,'23',[4,5]]))#1或者23或者[4,5]
     print(random.sample([1,'23',[4,5]],2))#列表元素任意2个组合
    print(random.uniform(1,3))#大于1小于3的小数,如1.927109612082716 item=[1,3,5,7,9] random.shuffle(item) #打乱item的顺序,相当于"洗牌" print(item)

    三。os模块
    os模块是与操作系统交互的一个接口
    os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
    os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
    os.curdir  返回当前目录: ('.')
    os.pardir  获取当前目录的父目录字符串名:('..')
    os.makedirs('dirname1/dirname2')    可生成多层递归目录
    os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
    os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
    os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
    os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    os.remove()  删除一个文件
    os.rename("oldname","newname")  重命名文件/目录
    os.stat('path/filename')  获取文件/目录信息
    os.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
    os.linesep    输出当前平台使用的行终止符,win下为"	
    ",Linux下为"
    "
    os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
    os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
    os.system("bash command")  运行shell命令,直接显示
    os.environ  获取系统环境变量
    os.path.abspath(path)  返回path规范化的绝对路径
    os.path.split(path)  将path分割成目录和文件名二元组返回
    os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
    os.path.basename(path)  返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
    os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
    os.path.isabs(path)  如果path是绝对路径,返回True
    os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
    os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
    os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
    os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
    os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
    os.path.getsize(path) 返回path的大小




    ④sys模块
    1 sys.argv           命令行参数List,第一个元素是程序本身路径
    2 sys.exit(n)        退出程序,正常退出时exit(0)
    3 sys.version        获取Python解释程序的版本信息
    4 sys.maxint         最大的Int值
    5 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    6 sys.platform       返回操作系统平台名称
     
     
     
     
  • 相关阅读:
    ubuntu 16.04上源码编译glog和gflags 编写glog-config.cmake和gflags-config.cmake | compile glog and glags on ubuntu 16.04
    Windows 10上源码编译glog和gflags 编写glog-config.cmake和gflags-config.cmake | compile glog and glags on windows from source
    windows 10上源码编译libjpeg-turbo和使用教程 | compile and use libjpeg-turbo on windows 10
    Ubuntu 16.04源码编译boost库 编写CMakeLists.txt | compile boost 1.66.0 from source on ubuntu 16.04
    如何在C++中使用boost库序列化自定义class ?| serialize and deserialize a class in cpp with boost
    Ubuntu 16.04上源码编译Poco并编写cmake文件 | guide to compile and install poco cpp library on ubuntu 16.04
    Windows 10上源码编译Poco并编写httpserver和tcpserver | compile and install poco cpp library on windows
    ubuntu 16.04 和 windows 10系统安装mysql 允许远程访问 | mysql user guide on ubuntu 16.04 and windows 10
    编写自定义cmake配置文件FindXXX.cmake或者xxx-config.cmake | cmake with user defined entry
    [Part 4] 在Windows 10上源码编译PCL 1.8.1支持VTK和QT,可视化三维点云
  • 原文地址:https://www.cnblogs.com/wangxiaoyienough/p/9272986.html
Copyright © 2011-2022 走看看