zoukankan      html  css  js  c++  java
  • day6_1

    一、加密模块

    1.hashlib

    >>> data=hashlib.md5()
    >>> data.update(b'hello')
    >>> print data.hexdigest()
    5d41402abc4b2a76b9719d911017c592
    View Code
    >>> data=hashlib.sha512()
    >>> data.update('123456')
    >>> print data.hexdigest()
    ba3253876aed6bc22d4a6ff53d8406c6ad864195ed144ab5c87621b6c233b548baeae6956df346ec8c17f5ea10f35ee3cbc514797ed7ddd3145464e2a0bab413
    View Code

    2.hmac

    >>> import hmac
    >>> h=hmac.new(b'hello')
    >>> h.update(b'test')
    >>> print h.hexdigest()
    0c7490a8663ddd7b947eeec4e2ce85f9
    View Code

     二、执行系统命令

    1、os.system   只能返回执行之后的状态码

    >>> result=os.system('ver')

    Microsoft Windows [版本 6.1.7601]
    >>> result
    0

    2、subprocess

    可以执行shell命令的相关模块和函数有:

    • os.system
    • os.spawn*
    • os.popen*          --废弃
    • popen2.*           --废弃
    • commands.*      --废弃,3.x中被移除
    import commands
    
    result = commands.getoutput('cmd')
    result = commands.getstatus('cmd')
    result = commands.getstatusoutput('cmd')

    以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。

    call 

    执行命令,返回状态

    ret = subprocess.call(["ls""-l"], shell=False)
    ret = subprocess.call("ls -l", shell=True)

    shell = True ,允许 shell 命令是字符串形式

    check_call

    执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

    subprocess.check_call(["ls""-l"])
    subprocess.check_call("exit 1", shell=True)

    check_output

    执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

    subprocess.check_output(["echo""Hello World!"])
    subprocess.check_output("exit 1", shell=True)

    subprocess.Popen(...)

    用于执行复杂的系统命令

    参数:

    • args:shell命令,可以是字符串或者序列类型(如:list,元组)
    • bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
    • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
    • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
    • close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
      所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
    • shell:同上
    • cwd:用于设置子进程的当前目录
    • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
    • universal_newlines:不同系统的换行符不同,True -> 同意使用 \n
    • startupinfo与createionflags只在windows下有效
      将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
    import subprocess
    ret1 = subprocess.Popen(["mkdir","t1"])
    ret2 = subprocess.Popen("mkdir t2", shell=True)

    终端输入的命令分为两种:

    • 输入即可得到输出,如:ifconfig
    • 输入进行某环境,依赖再输入,如:python
    import subprocess
    
    obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)

    import subprocess

    obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    obj.stdin.write('print 1 \n ')
    obj.stdin.write('print 2 \n ')
    obj.stdin.write('print 3 \n ')
    obj.stdin.write('print 4 \n ')
    obj.stdin.close()

    cmd_out = obj.stdout.read()
    obj.stdout.close()
    cmd_error = obj.stderr.read()
    obj.stderr.close()

    print cmd_out
    print cmd_error

    import subprocess

    obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    obj.stdin.write('print 1 \n ')
    obj.stdin.write('print 2 \n ')
    obj.stdin.write('print 3 \n ')
    obj.stdin.write('print 4 \n ')

    out_error_list = obj.communicate()
    print out_error_list

    import subprocess
    
    obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out_error_list = obj.communicate('print "hello"')
    print out_error_list

     shutil  文件复制

    import shutil
    
    shutil.make_archive('123','gztar')#打包格式为gz.tar
    shutil.make_archive('123','bztar')#打包格式为gz.tar
    shutil.make_archive('123','zip')#打包格式为zip
    
    shutil.copyfile('123.txt','456.txt')#复制文件
    shutil.copy('1/1.txt','test')#把目录中的文件复制到指定的目录中
    shutil.rmtree('1')#递归删除目录

    三、持久化

    1、json

    2、pickle

    3、shelve

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

    import shelve
    
    def shelve_write():
        dict1={'username':'root','password':123,'host':'localhost','prot':3306}
        list1=['name','root','db','mysql']
    
        d=shelve.open('shelve_test.txt')
        d['D1']=dict1  #持久化字典
        d['L1']=list1  #持久化列表
        d.close()
    
    
    def shelve_read():
        d=shelve.open('shelve_test.txt')
        print(d['D1']) #读取字典
        print(d['L1']) #读取列表
    shelve_read()
    View Code

    四、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>
    import xml.etree.ElementTree as ET
    
    tree=ET.parse('test.xml')
    root=tree.getroot()
    # print root.tag
    
    
    #遍历xml文档
    for data in root:
        print data.tag,data.attrib
        for i in   data:
            print i.tag,i.text
    
    
    print '------'
    #只遍历year节点
    for node in   root.iter('rank'):
        print node.tag,node.text
    
    
    # #修改year节点
    for node  in root.iter('year'):
        new_year=int(node.text)+20
        node.text=str(new_year)
        node.set('update','yes')
    tree.write('xym.xml')
    
    
    
    #删除
    for country in root.findall('country'):
       rank = int(country.find('rank').text)
       if rank > 50:
         root.remove(country)
    tree.write('output.xml')
    
    
    
    #创建xml文档
    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("test11.xml", encoding="utf-8",xml_declaration=True)
    
    ET.dump(new_xml) #打印生成的格式
    View Code

     configparser

    import  configparser
    
    #创建配置文件
    config = configparser.ConfigParser() #调用模块中的类,并实例化
    config['DEFAULT']={'name':'xym'}
    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)
    
    
    #查询指定的内容
    print(config.read('example.ini'))
    result=config.sections()
    print(result)
    print(config['DEFAULT']['forwardx11'])
    print(config.defaults())
    
    for key in  config['topsecret.server.com']:
        print(key)
    
    #读取配置
    print(config['topsecret.server.com'])
    config.read('example.ini')
    print(config.sections())
    print(config.options('bitbucket.org'))
    print(config.items('bitbucket.org'))
    print(config.get('bitbucket.org','user'))#获取value
    print(config.getint('bitbucket.org','user'))#如果值不为数值为报错
    
    
    #删除
    data=config.remove_section('bitbucket.org')
    config.write(open('i.cfg','wb'))

    logging 日志

    日志等级:
    
    CRITICAL = 50
    FATAL = CRITICAL
    ERROR = 40
    WARNING = 30
    WARN = WARNING
    INFO = 20
    DEBUG = 10
    NOTSET = 0
    
    只有大于当前日志等级的操作才会被记录
    import logging
    
    logger=logging.getLogger('test-log')  #实例化
    logger.setLevel(logging.DEBUG)        #设置全局的日志等级
    
    ch=logging.StreamHandler()            #屏幕
    ch.setLevel(logging.DEBUG)            #屏幕的日志等级,输出的日志级别大于DEBUG才显示
    
    
    fh=logging.FileHandler('access.log')  #日志记录到文件
    fh.setLevel(logging.WARN)             #文件的日志等级,输出的日志级别大于DEBUG才记录
    
    
    formatter=logging.Formatter('%(asctime)s -%(name)s -%(levelname)s - %(message)s') #日志格式
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)


    logger.addHandler(ch)
    logger.addHandler(fh)


    #logger.debug(
    'debug message')
    #logger.info(
    'info message')
    #logger.warning(
    'warning message')
    #logger.error(
    'error message')
    #logger.critical(
    'critical message')

     

  • 相关阅读:
    vue实现图片路径传送
    title中添加小图标
    张钊的第一份作业
    张钊的第二份作业
    在Windows Server 2008 R2环境下安装活动目录失败的一个解决方法
    如何把SubVersion的服务程序变为Window后台服务形式
    一个关于静态方法调用的问题。
    WCF配置中遇到的问题:如何把Hostname修改成IP
    删除Visual Studio最近的项目(转载)
    有时候用ifstream或ofstream打开带有中文路径的文件会失败
  • 原文地址:https://www.cnblogs.com/xuyanmei/p/5206374.html
Copyright © 2011-2022 走看看