zoukankan      html  css  js  c++  java
  • python 常用模块

    导入模块
    import modulename

    导入多个模块
    import modulename,modulename,modulename

    导入模块并取个别名
    import modulename as newname

    从sys模块导入argv方法
    from sys import argv

    getpass 模块

    输入密码时,如果想要不可见,需要利用getpass 模块中的 getpass方法

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    import getpass
     
    # 将用户输入的内容赋值给 name 变量
    pwd = getpass.getpass("请输入密码:")
     
    # 打印输入的内容
    print pwd

    sys 模块

    sys.argv           命令行参数List,第一个元素是程序本身路径
    sys.exit(n)        退出程序,正常退出时exit(0)
    sys.version        获取Python解释程序的版本信息
    sys.maxint         最大的Int值
    sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    sys.platform       返回操作系统平台名称
    sys.stdout.write('please:')
    val = sys.stdin.readline()[:-1]

    进度条

    import sys
    import time
    for i in range(1,100):
        sys.stdout.write("=")
        sys.stdout.flush()
        time.sleep(0.3)

    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    输出用于分割文件路径的字符串
    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.split()函数,这样可以把一个路径拆分为两部分,后一部分总是最后级别的目录或文件名:

    >>> os.path.split('/Users/michael/testdir/file.txt')
    ('/Users/michael/testdir', 'file.txt')

    os.path.splitext()可以直接让你得到文件扩展名,很多时候非常方便:

    >>> os.path.splitext('/path/to/file.txt')
    ('/path/to/file', '.txt')

     time模块

    import time
    print(time.time())  时间戳
    print(time.strftime('%Y%m%d-%H:%M:%S')) 格式化的字符串
    print(time.localtime()) 结构化时间



    # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
    # print(time.altzone)  #返回与utc时间的时间差,以秒计算
    # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
    # print(time.localtime()) #返回本地时间 的struct time对象格式
    # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式

    # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
    #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上



    # 日期字符串 转成  时间戳
    # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
    # print(string_2_struct)
    # #
    # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
    # print(struct_2_stamp)



    #将时间戳转为字符串格式
    # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
    # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式





    #时间加减
    import datetime

    # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
    #print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
    # print(datetime.datetime.now() )
    # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
    # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
    # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
    # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分


    #
    # c_time  = datetime.datetime.now()
    # print(c_time.replace(minute=3,hour=2)) #时间替换

     random模块

    import random
    print random.random()
    print random.randint(1,2)
    print random.randrange(1,10)

    生成验证码

    import random
    check_code=""
    for i in range(4):
        current=random.randint(0,4)
        if current !=i:
            tmp=str(chr(random.randint(65,90)))
        else:
            tmp=random.randint(0,9)
        check_code=check_code+str(tmp)
    print(check_code)

    pickle模块

    写入

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-
    import pickle
    data={
        'name':'sun',
        'age':24,
        'sex':'man',
    }
    
    with open('test.txt','wb') as f:
        pickle.dump(data,f)

    读取

    import pickle
    
    with open('test.txt','rb') as f:
        data=pickle.load(f)
    print(data)

    Json模块

    写入

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-
    import json
    data={
        'name':'ibm',
        'age':24,
        'sex':'man',
    }
    
    with open('test.txt','w') as f:
        json.dump(data,f)

    读取

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-
    import json
    
    with open('test.txt','r') as f:
        data=json.load(f)
    print(data)

    shutil

    高级的 文件、文件夹、压缩包 处理模块

    shutil.copyfileobj(fsrc, fdst[, length])
    将文件内容拷贝到另一个文件中,可以部分内容

    def copyfileobj(fsrc, fdst, length=16*1024):
        """copy data from file-like object fsrc to file-like object fdst"""
        while 1:
            buf = fsrc.read(length)
            if not buf:
                break
            fdst.write(buf)
    View Code

    shutil.copyfile(src, dst)
    拷贝文件

    def copyfile(src, dst):
        """Copy data from src to dst"""
        if _samefile(src, dst):
            raise Error("`%s` and `%s` are the same file" % (src, dst))
    
        for fn in [src, dst]:
            try:
                st = os.stat(fn)
            except OSError:
                # File most likely does not exist
                pass
            else:
                # XXX What about other special files? (sockets, devices...)
                if stat.S_ISFIFO(st.st_mode):
                    raise SpecialFileError("`%s` is a named pipe" % fn)
    
        with open(src, 'rb') as fsrc:
            with open(dst, 'wb') as fdst:
                copyfileobj(fsrc, fdst)
    View Code

    shutil.copymode(src, dst)
    仅拷贝权限。内容、组、用户均不变

    def copymode(src, dst):
        """Copy mode bits from src to dst"""
        if hasattr(os, 'chmod'):
            st = os.stat(src)
            mode = stat.S_IMODE(st.st_mode)
            os.chmod(dst, mode)
    View Code

    shutil.copystat(src, dst)
    拷贝状态的信息,包括:mode bits, atime, mtime, flags

    shutil.copystat(src, dst)
    拷贝状态的信息,包括:mode bits, atime, mtime, flags
    View Code

    shutil.copy(src, dst)
    拷贝文件和权限

    def copy(src, dst):
        """Copy data and mode bits ("cp src dst").
    
        The destination may be a directory.
    
        """
        if os.path.isdir(dst):
            dst = os.path.join(dst, os.path.basename(src))
        copyfile(src, dst)
        copymode(src, dst)
    View Code

    shutil.copy2(src, dst)
    拷贝文件和状态信息

    def copy2(src, dst):
        """Copy data and all stat info ("cp -p src dst").
    
        The destination may be a directory.
    
        """
        if os.path.isdir(dst):
            dst = os.path.join(dst, os.path.basename(src))
        copyfile(src, dst)
        copystat(src, dst)
    View Code

    shutil.ignore_patterns(*patterns)
    shutil.copytree(src, dst, symlinks=False, ignore=None)
    递归的去拷贝文件

    例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

    shutil.rmtree(path[, ignore_errors[, onerror]])
    递归的去删除文件

    shutil.make_archive(base_name, format,...)

    创建压缩包并返回文件路径,例如:zip、tar

      • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
        如:www                        =>保存至当前路径
        如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
      • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
      • root_dir: 要压缩的文件夹路径(默认当前目录)
      • owner: 用户,默认当前用户
      • group: 组,默认当前组
      • logger: 用于记录日志,通常是logging.Logger对象
    #将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
     
    import shutil
    ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
     
     
    #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
    import shutil
    ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

    shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

    import zipfile
    
    # 压缩
    z = zipfile.ZipFile('laxi.zip', 'w')
    z.write('a.log')
    z.write('data.data')
    z.close()
    
    # 解压
    z = zipfile.ZipFile('laxi.zip', 'r')
    z.extractall()
    z.close()
    
    zipfile 压缩解压
    View Code
    import tarfile
    
    # 压缩
    tar = tarfile.open('your.tar','w')
    tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
    tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
    tar.close()
    
    # 解压
    tar = tarfile.open('your.tar','r')
    tar.extractall()  # 可设置解压地址
    tar.close()
    
    tarfile 压缩解压
    View Code

    shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

    import shelve
    sw = shelve.open('shelve_test.pkl') # 创建shelve对象
     
    name = ['13', '14', '145', 6] # 创建一个列表
    dist_test = {"k1":"v1", "k2":"v2"}
    sw['name'] = name # 将列表持久化保存
    sw['dist_test'] = dist_test
    sw.close() # 关闭文件,必须要有
     
    sr = shelve.open('shelve_test.pkl')
    print(sr['name']) # 读出列表
    print(sr['dist_test']) # 读出字典
    sr.close()

    xml处理模块

    xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

    xml的格式如下,就是通过<>节点来区别数据结构的:

    <?xml version="1.0"?>
    <data>
        <country name="Liechtenstein">
            <rank updated="yes">2</rank>
            <year>2008</year>
            <gdppc>141100</gdppc>
            <neighbor name="Austria" direction="E"/>
            <neighbor name="Switzerland" direction="W"/>
        </country>
        <country name="Singapore">
            <rank updated="yes">5</rank>
            <year>2011</year>
            <gdppc>59900</gdppc>
            <neighbor name="Malaysia" direction="N"/>
        </country>
        <country name="Panama">
            <rank updated="yes">69</rank>
            <year>2011</year>
            <gdppc>13600</gdppc>
            <neighbor name="Costa Rica" direction="W"/>
            <neighbor name="Colombia" direction="E"/>
        </country>
    </data>
    View Code

    xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml   

    import xml.etree.ElementTree as ET
     
    tree = ET.parse("xmltest.xml")
    root = tree.getroot()
    print(root.tag)
     
    #遍历xml文档
    for child in root:
        print(child.tag, child.attrib)
        for i in child:
            print(i.tag,i.text)
     
    #只遍历year 节点
    for node in root.iter('year'):
        print(node.tag,node.text)

    修改和删除xml文档内容

    import xml.etree.ElementTree as ET
     
    tree = ET.parse("xmltest.xml")
    root = tree.getroot()
     
    #修改
    for node in root.iter('year'):
        new_year = int(node.text) + 1
        node.text = str(new_year)
        node.set("updated","yes")
     
    tree.write("xmltest.xml")
     
     
    #删除node
    for country in root.findall('country'):
       rank = int(country.find('rank').text)
       if rank > 50:
         root.remove(country)
     
    tree.write('output.xml')
    View Code

    自己创建xml文档

    import xml.etree.ElementTree as ET
     
     
    new_xml = ET.Element("namelist")
    name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
    age = ET.SubElement(name,"age",attrib={"checked":"no"})
    sex = ET.SubElement(name,"sex")
    sex.text = '33'
    name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
    age = ET.SubElement(name2,"age")
    age.text = '19'
     
    et = ET.ElementTree(new_xml) #生成文档对象
    et.write("test.xml", encoding="utf-8",xml_declaration=True)
     
    ET.dump(new_xml) #打印生成的格式 
    View Code

    ConfigParser模块

    ConfigParser模块是用来处理配置文件的包,配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。常见很多服务的都是类似这种格式的,比如MySQL

    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
     
    [bitbucket.org]
    User = hg
     
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no
    View Code

    写配置文件

    import configparser
     
    config = configparser.ConfigParser()
    config["DEFAULT"] = {'ServerAliveInterval': '45',
                          'Compression': 'yes',
                         'CompressionLevel': '9'}
     
    config['bitbucket.org'] = {}
    config['bitbucket.org']['User'] = 'hg'
    config['topsecret.server.com'] = {}
    topsecret = config['topsecret.server.com']
    topsecret['Host Port'] = '50022'     # mutates the parser
    topsecret['ForwardX11'] = 'no'  # same here
    config['DEFAULT']['ForwardX11'] = 'yes'
    with open('example.ini', 'w') as configfile:
       config.write(configfile)
    View Code

    读取配置文件

     

    >>> import configparser
    >>> config = configparser.ConfigParser()
    >>> config.sections()
    []
    >>> config.read('example.ini')
    ['example.ini']
    >>> config.sections()
    ['bitbucket.org', 'topsecret.server.com']
    >>> 'bitbucket.org' in config
    True
    >>> 'bytebong.com' in config
    False
    >>> config['bitbucket.org']['User']
    'hg'
    >>> config['DEFAULT']['Compression']
    'yes'
    >>> topsecret = config['topsecret.server.com']
    >>> topsecret['ForwardX11']
    'no'
    >>> topsecret['Port']
    '50022'
    >>> for key in config['bitbucket.org']: print(key)
    ...
    user
    compressionlevel
    serveraliveinterval
    compression
    forwardx11
    >>> config['bitbucket.org']['ForwardX11']
    'yes'
    View Code

     

    configparser增删改查语法

    [section1]
    k1 = v1
    k2:v2
      
    [section2]
    k1 = v1
     
    import ConfigParser
      
    config = ConfigParser.ConfigParser()
    config.read('i.cfg')
      
    # ########## 读 ##########
    #secs = config.sections()
    #print secs
    #options = config.options('group2')
    #print options
      
    #item_list = config.items('group2')
    #print item_list
      
    #val = config.get('group1','key')
    #val = config.getint('group1','key')
      
    # ########## 改写 ##########
    #sec = config.remove_section('group1')
    #config.write(open('i.cfg', "w"))
      
    #sec = config.has_section('wupeiqi')
    #sec = config.add_section('wupeiqi')
    #config.write(open('i.cfg', "w"))
      
      
    #config.set('group2','k1',11111)
    #config.write(open('i.cfg', "w"))
      
    #config.remove_option('group2','age')
    #config.write(open('i.cfg', "w"))
    View Code

    hashlib模块  

    用于加密相关的操作

    import hashlib
     
    m = hashlib.md5()
    m.update(b"Hello")
    m.update(b"It's me")
    print(m.digest())
    m.update(b"It's been a long time since last time we ...")
     
    print(m.digest()) #2进制格式hash
    print(len(m.hexdigest())) #16进制格式hash
    '''
    def digest(self, *args, **kwargs): # real signature unknown
        """ Return the digest value as a string of binary data. """
        pass
     
    def hexdigest(self, *args, **kwargs): # real signature unknown
        """ Return the digest value as a string of hexadecimal digits. """
        pass
     
    '''
    import hashlib
     
    # ######## md5 ########
     
    hash = hashlib.md5()
    hash.update('admin')
    print(hash.hexdigest())
     
    # ######## sha1 ########
     
    hash = hashlib.sha1()
    hash.update('admin')
    print(hash.hexdigest())
     
    # ######## sha256 ########
     
    hash = hashlib.sha256()
    hash.update('admin')
    print(hash.hexdigest())
     
     
    # ######## sha384 ########
     
    hash = hashlib.sha384()
    hash.update('admin')
    print(hash.hexdigest())
     
    # ######## sha512 ########
     
    hash = hashlib.sha512()
    hash.update('admin')
    print(hash.hexdigest())
    View Code

    subprocess模块

    #执行命令,返回命令执行状态 , 0 or 非0
    >>> retcode = subprocess.call(["ls", "-l"])
    
    #执行命令,如果命令结果为0,就正常返回,否则抛异常
    >>> subprocess.check_call(["ls", "-l"])
    0
    
    #接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
    >>> subprocess.getstatusoutput('ls /bin/ls')
    (0, '/bin/ls')
    
    #接收字符串格式命令,并返回结果
    >>> subprocess.getoutput('ls /bin/ls')
    '/bin/ls'
    
    #执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
    >>> res=subprocess.check_output(['ls','-l'])
    >>> res
    b'total 0
    drwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM
    '
    
    #上面那些方法,底层都是封装的subprocess.Popen
    poll()
    Check if child process has terminated. Returns returncode
    
    wait()
    Wait for child process to terminate. Returns returncode attribute.
    
    
    terminate() 杀掉所启动进程
    communicate() 等待任务结束
    
    stdin 标准输入
    
    stdout 标准输出
    
    stderr 标准错误
    
    pid
    The process ID of the child process.
    
    #例子
    >>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
    >>> p.stdout.read()
    b'/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% /
    '
    View Code

    subprocess.Popen()

    p = subprocess.Popen("find / -size +1000000 -exec ls -shl {} ;",shell=True,stdout=subprocess.PIPE)
    print(p.stdout.read())

    需要交互的命令示例

    import subprocess
     
    obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    obj.stdin.write('print 1 
     ')
    obj.stdin.write('print 2 
     ')
    obj.stdin.write('print 3 
     ')
    obj.stdin.write('print 4 
     ')
     
    out_error_list = obj.communicate(timeout=10)
    print out_error_list
    View Code

    subprocess实现sudo 自动输入密码

    import subprocess
     
    def mypass():
        mypass = '123' #or get the password from anywhere
        return mypass
     
    echo = subprocess.Popen(['echo',mypass()],
                            stdout=subprocess.PIPE,
                            )
     
    sudo = subprocess.Popen(['sudo','-S','iptables','-L'],
                            stdin=echo.stdout,
                            stdout=subprocess.PIPE,
                            )
     
    end_of_pipe = sudo.stdout
     
    print "Password ok 
     Iptables Chains %s" % end_of_pipe.read()
    View Code

     logging

    很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()info()warning()error() and critical() 5个级别,下面我们看一下怎么用。

    import logging
     
    logging.warning("user [root] attempted wrong password more than 3 times")
    logging.critical("server is down")
     
    #输出
    WARNING:root:user [root] attempted wrong password more than 3 times
    CRITICAL:root:server is down

    把日志写到文件里

    import logging
     
    logging.basicConfig(filename='example.log',level=logging.INFO)
    logging.debug('This message should go to the log file')
    logging.info('So should this')
    logging.warning('And this, too')

    日志格式忘记加上时间
    
    import logging
    logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
    logging.warning('is when this event was logged.')
     
    #输出
    12/12/2010 11:46:36 AM is when this event was logged.

     

     

  • 相关阅读:
    小师妹学JVM之:JIT中的PrintCompilation
    八张图彻底了解JDK8 GC调优秘籍-附PDF下载
    区块链系列教程之:比特币中的网络和区块链
    从印度兵力分布聊聊Mybatis中#和$的区别
    区块链系列教程之:比特币的钱包与交易
    小师妹学JVM之:JIT中的LogCompilation
    从发布-订阅模式谈谈 Flask 的 Signals
    基于 Ajax 请求的 Flask-Login 认证
    解决 openpyxl 垂直分页符和水平分页符同时添加的问题
    用 python 抓取知乎指定回答下的视频
  • 原文地址:https://www.cnblogs.com/sxlnnnn/p/6363023.html
Copyright © 2011-2022 走看看