zoukankan      html  css  js  c++  java
  • python之旅六【第六篇】模块

    json和pickle

    用于序列化的两个模块
    json,用于字符串 和 python数据类型间进行转换
    pickle,用于python特有的类型 和 python的数据类型间进行转换

    json模块提供了四个功能:dumps、dump、loads、load
    pickle模块提供了四个功能:dumps、dump、loads、load

    json dumps把数据类型转换成字符串 dump把数据类型转换成字符串并存储在文件中  loads把字符串转换成数据类型  load把文件打开从字符串转换成数据类型

    pickle同理

    现在有个场景在不同设备之间进行数据交换很low的方式就是传文件,dumps可以直接把服务器A中内存的东西发给其他服务器,比如B服务器、
    在很多场景下如果用pickle的话那A的和B的程序都的是python程序这个是不现实的,很多时候都是不同的程序之间的内存交换怎么办?就用到了json(和html类似的语言)
    并且josn能dump的结果更可读,那么有人就问了,那还用pickle做什么不直接用josn,是这样的josn只能把常用的数据类型序列化(列表、字典、列表、字符串、数字、),比如日期格式、类对象!josn就不行了。
    为什么他不能序列化上面的东西呢?因为josn是跨语言的!
    具体实例如下
     1 import json
     2 '''
     3 json dumps把数据类型转换成字符串 dump把数据类型转换成字符串并存储在文件中
     4 loads把字符串转换成数据类型  load把文件打开从字符串转换成数据类型
     5 '''
     6 name = {'name':'dicky','age':19}
     7 print type(json.dumps(name))   #数据类型转换成字符串
     8 print json.dumps(name)
     9 print json.loads(json.dumps(name))
    10 print type(json.loads(json.dumps(name))) #字符串转换成字典
    11 
    12 结果
    13 <type 'str'>
    14 {"age": 19, "name": "dicky"}
    15 {u'age': 19, u'name': u'dicky'}
    16 <type 'dict'>
     1 '''
     2 dump把数据类型转换成字符串并存储在文件中
     3  load把文件打开从字符串转换成数据类型
     4  '''
     5 new_list = {'age':19,'work':'IT'}
     6 with open ('test1','w') as openfile:
     7     json.dump(new_list,openfile)
     8     print "以上就是dump......."
     9 
    10 with open('test1','rb') as readfile:
    11     result=json.load(readfile)
    12     print "load完成",type(result)
    13     print result
    14 
    15 
    16 结果
    17 以上就是dump.......
    18 load完成 <type 'dict'>
    19 {u'age': 19, u'work': u'IT'}

     ConfigParser

    用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。

     1 import ConfigParser
     2 
     3 '''
     4 test1
     5 [section1]
     6 name = dicky
     7 k2 = v2
     8 age = 13
     9 
    10 [section2]
    11 k1 = v1
    12 work=IT
    13 [shuaige]
    14 name = dicky
    15 '''
    16 config=ConfigParser.ConfigParser()
    17 config.read('test1')
    18 #读取
    19 sec=config.sections()
    20 print sec
    21 option=config.options('section1')
    22 print option
    23 item=config.items('section1')
    24 print item
    25 val = config.get('section1','name')
    26 print val
    27 val1 = config.getint('section1','age')
    28 print val1
    29 #修改
    30 sec1=config.remove_section('section3')  #删除色彩tion3
    31 config.write(open('test1','w'))
    32 # sec = config.add_section('shuaige')
    33 # config.write(open('test1','w'))
    34 #
    35 # config.set('shuaige','name','dicky')
    36 # config.write(open('test1','w'))
    37 
    38 config.remove_option('section2','work')
    39 config.write(open('test1','w'))
    40 
    41 结果
    42 ['section1', 'section2', 'shuaige']
    43 ['name', 'k2', 'age']
    44 [('name', 'dicky'), ('k2', 'v2'), ('age', '13')]
    45 dicky
    46 13

     操作系统相关命令

    os.system() #执行系统命令

    其他的都废弃掉了,以后使用subprocess代替了

    主要介绍subprocess

    call

    1 subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
    2 执行命令,返回状态码
    3 ret = subprocess.call(["ls", "-l"], shell=False)
    4 ret = subprocess.call("ls -l", shell=True)
    5 shell = True ,允许 shell 命令是字符串形式,也就是使用shell来执行,一般情况下,我们要使用shell=False,也是默认的一种形式,模式就是shell=False

    check_call

    1 subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
    2 执行命令,如果执行状态码是 0 ,则返回0,否则抛异常
    3 subprocess.check_call(["ls", "-l"])
    4 subprocess.check_call("exit 1", shell=True)

    check_output

     1 subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
     2 执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常
     3 subprocess.check_output(["echo", "Hello World!"])
     4 subprocess.check_output("exit 1", shell=True)
     5 捕获异常
     6 若要在结果中捕获标准错误,可以使用 stderr=subprocess.STDOUT
     7 >>> subprocess.check_output(
     8 ...     "ls non_existent_file; exit 0",
     9 ...     stderr=subprocess.STDOUT,
    10 ...     shell=True)
    11 'ls: non_existent_file: No such file or directory
    '

    Popen

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

     args

    如果args 是一个字符串,该字符串将解释为要执行的程序的名字或路径。然而,这只能在不传递参数给程序时可行。

    如下解决

    1 前提是创建好文件egg.txt
    2 >>> import shlex, subprocess
    3 >>> command_line = raw_input()
    4 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
    5 >>> args = shlex.split(command_line)
    6 >>> print args
    7 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
    8 >>> p = subprocess.Popen(args) # Success!

    简单执行命令

    1 ret1 = subprocess.Popen(["mkdir","t1"])
    2 ret2 = subprocess.Popen("mkdir t2", shell=True)

    Popen 类的实例具有以下方法

     1 Popen.poll()  检查子进程是否已经终止
     2 Popen.wait()  等待子进程终止
     3 Popen.communicate(input=None)
     4 与进程交互:将数据发送到标准输入。从标准输出和标准错误读取数据,直至到达文件末尾。等待进程终止。可选的input 参数应该是一个要发送给子进程的字符串,如果没有数据要发送给子进程则应该为None。
     5 注意如果你需要发送数据到进程的标准输入,你需要以stdin=PIPE创建Popen对象。类似地,在结果的元组中若要得到非None的数据,你还需要给出stdout=PIPE和/或stderr=PIPE。
     6 Popen.send_signal(signal)   发送信号signal 给子进程。
     7 Popen.terminate()   终止子进程。
     8 Popen.kill()  杀死子进程。
     9 Popen.stdin   如果stdin 参数为PIPE,则该属性为一个文件对象,它提供子进程的输入。否则,为None。
    10 Popen.stdout   如果stdout 参数为PIPE,则该属性是一个文件对象,它提供子进程中的输出。否则,为None。
    11 Popen.stderr   如果stderr 参数为PIPE,则该属性是一个文件对象,它提供子进程中的错误输出。否则,为None。
    12 Popen.pid   子进程的进程ID。
    13 注意如果你设置shell 参数为True,那么它是产生的shell的进程ID。
    View Code

     依赖,进入某环境输入

    import subprocess
    
    obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)

    保存输出

     1 import subprocess
     2 
     3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     4 out_error_list = obj.communicate('print "hello"')
     5 print out_error_list
     6 
     7 import subprocess
     8 
     9 obj = subprocess.Popen(["ls"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    10 out_error_list = obj.communicate()
    11 print out_error_list

    另外一种

    stdout.read()

     1 import subprocess
     2 
     3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     4 obj.stdin.write('print 1 
     ')
     5 obj.stdin.write('print 2 
     ')
     6 obj.stdin.write('print 3 
     ')
     7 obj.stdin.write('print 4 
     ')
     8 obj.stdin.close()
     9 
    10 cmd_out = obj.stdout.read()
    11 obj.stdout.close()
    12 cmd_error = obj.stderr.read()
    13 obj.stderr.close()
    14 
    15 print cmd_out
    16 print cmd_error

    加密模块

     md5已经废弃

    1 import md5
    2 hash = md5.new()
    3 hash.update('admin')
    4 print hash.hexdigest()
    View Code

    sha废弃

    1 import sha
    2 hash = sha.new()
    3 hash.update('admin')
    4 print hash.hexdigest()
    View Code

     hashlib替代了以上的加密

    1 import  hashlib
    2 hash = hashlib.md5()
    3 hash.update('admin')
    4 print hash.hexdigest()
    1 sha加密
    2 hash = hashlib.sha1()
    3 hash.update('admin')
    4 print hash.hexdigest()

    其他的一样,就不一一列举了

    以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。

    import hashlib
     
    # ######## md5 ########
     
    hash = hashlib.md5('898oaFs09f')  #自定义的key
    hash.update('admin')
    print hash.hexdigest()

    还不够吊?python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密

    1 import hmac
    2 h = hmac.new('wueiqi')
    3 h.update('hellowo')
    4 print h.hexdigest()

     日志模块logging

     简单用法

     1 import logging
     2  
     3 logging.basicConfig(filename='log.log',
     4                     format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
     5                     datefmt='%Y-%m-%d %H:%M:%S %p',
     6                     level=10)
     7  
     8 logging.debug('debug')
     9 logging.info('info')
    10 logging.warning('warning')
    11 logging.error('error')
    12 logging.critical('critical')
    13 logging.log(10,'log')
    14 
    15 级别
    16 CRITICAL = 50
    17 FATAL = CRITICAL
    18 ERROR = 40
    19 WARNING = 30
    20 WARN = WARNING
    21 INFO = 20
    22 DEBUG = 10
    23 NOTSET = 0

     详细参考链接:http://www.jianshu.com/p/feb86c06c4f4

  • 相关阅读:
    [windows phone开发]新生助手的开发过程与体会三
    安卓真机调试 出现Installation error: INSTALL_FAILED_UPDATE_INCOMPATIBLE....
    Easyui columns列图片移位问题!!!
    Easyui 去掉datagrid 行的样式,并点击checked 改边行颜色!
    安卓手机 虚拟键盘输入用 position:fixed解决 !!!
    Linux下用Perl产生新的EXCEL文档 zhumao
    在 Perl 中使用内联 zhumao
    牛郎织女 zhumao
    打开.bz2文件 zhumao
    perl中的特殊内置变量(转) zhumao
  • 原文地址:https://www.cnblogs.com/Dicky-Zhang/p/7406736.html
Copyright © 2011-2022 走看看