week7-configparser-hashlib-subprocess-xml模块

configparser模块

举例文件a.ini:

[alex]
name = alex
age = 73
is_admin = yes
salary = 100000000000
[egon] 
name = egon
age = 84
is_admin = no
salary = 100000

  

常用操作:

import configparser

config=configparser.ConfigParser()
config.read('a.ini')

#取配置
print(config.sections()) #看标题
print(config.options(config.sections()[0])) #查看某个标题下的配置项
res=config.get('alex','name')#查看某个标题下的某个配置项的值
print(type(res))

res1=config.getint('egon','age')#查看某个标题下的某个配置项的值
print(type(res1))

res1=config.getboolean('egon','is_admin')#查看某个标题下的某个配置项的值
print(type(res1))

res1=config.getfloat('egon','salary')#查看某个标题下的某个配置项的值
print(type(res1))

#修改
config.remove_section('alex')
config.remove_option('egon','age')
config.add_section('alex')
config.set('alex','name','SB')
config.write(open('a.ini','w'))

hashlib模块

常规操作演示:

import hashlib
#---1
m=hashlib.md5()
m.update('hello'.encode('utf-8'))
m.update('world'.encode('utf-8'))
print(m.hexdigest())
#---2
m=hashlib.md5()
m.update('helloworld'.encode('utf-8'))
print(m.hexdigest())
#---3
m=hashlib.md5('helloworld'.encode('utf-8'))
print(m.hexdigest())
#---4
m=hashlib.md5('h'.encode('utf-8'))
m.update('elloworld'.encode('utf-8'))
print(m.hexdigest())
#以上4种方式print值是相同的
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#给文件计算md5可以用下面的方法
m=hashlib.md5()
with open('a.xml','rb') as f:
    for line in f:
        m.update(line)
print(m.hexdigest())

#下面这种方式给文件计算md5值,如果文件大,相当耗费内存不推荐使用
m=hashlib.md5()
with open('a.xml','rb') as f:
    m.update(f.read())
print(m.hexdigest())

# 加盐  基本就很难被暴力破解了,因为对方不知道具体加了哪些字符串
password='beijing3714'
m=hashlib.md5('yihangbailushangqingtian'.encode('utf-8'))
m.update(password.encode('utf-8'))

passwd_md5=m.hexdigest()

print(passwd_md5)

#hmac强制加字符串计算md5值
import hmac

h=hmac.new('hello'.encode('utf-8'))
h.update('world'.encode('utf-8'))
print(h.hexdigest())

h=hmac.new('hello'.encode('utf-8'))
h.update('w'.encode('utf-8'))
h.update('or'.encode('utf-8'))
h.update('ld'.encode('utf-8'))
print(h.hexdigest())

subprocess模块

subprocess最早在2.4版本引入。用来生成子进程,并可以通过管道连接他们的输入/输出/错误,以及获得他们的返回值。

# subprocess用来替换多个旧模块和函数
 
os.system
os.spawn*
os.popen*
popen2.*
commands.*

  运行python的时候,我们都是在创建并运行一个进程,linux中一个进程可以fork一个子进程,并让这个子进程exec另外一个程序。在python中,我们通过标准库中的subprocess包来fork一个子进程,并且运行一个外部的程序。subprocess包中定义有数个创建子进程的函数,这些函数分别以不同的方式创建子进程,所欲我们可以根据需要来从中选取一个使用。另外subprocess还提供了一些管理标准流(standard stream)和管道(pipe)的工具,从而在进程间使用文本通信。

常规操作演示:

call 和check_all 如果在程序中使用需要等待调用的命令支持完才能进行下一步,如果不想等待就开启子进程。

#call  执行命令,返回状态码,shell = True允许shell命令时字符串形式
>>> subprocess.call("date",shell=True)
Fri Aug 18 17:07:16 CST 2017
0
>>> subprocess.call("dddddd",shell=True)
/bin/sh: dddddd: command not found
127

#check_all  执行命令,如果执行状态码是0,则返回0,否则抛出异常
>>> subprocess.check_call("date",shell=True)
Fri Aug 18 17:08:26 CST 2017
0
>>> subprocess.check_call("dddddd",shell=True)
/bin/sh: dddddd: command not found
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.4/subprocess.py", line 558, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'dddddd' returned non-zero exit status 127

#####call官方说明
def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
#####check_call官方说明
def check_call(*popenargs, **kwargs):
    """Run command with arguments.  Wait for command to complete.  If
    the exit code was zero then return, otherwise raise
    CalledProcessError.  The CalledProcessError object will have the
    return code in the returncode attribute.

    The arguments are the same as for the call function.  Example:

    check_call(["ls", "-l"])
    """

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

>>> subprocess.check_output("date",shell=True)
b'Fri Aug 18 17:19:38 CST 2017\n'
>>> 
>>> 
>>> subprocess.check_output("dddd",shell=True)
/bin/sh: dddd: command not found
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.4/subprocess.py", line 617, in check_output
    raise CalledProcessError(retcode, process.args, output=output)
subprocess.CalledProcessError: Command 'dddd' returned non-zero exit status 127
#####官方说明
def check_output(*popenargs, timeout=None, **kwargs):
    r"""Run command with arguments and return its output.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor.  Example:

    >>> check_output(["ls", "-l", "/dev/null"])
    b'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.

    >>> check_output(["/bin/sh", "-c",
    ...               "ls -l non_existent_file ; exit 0"],
    ...              stderr=STDOUT)
    b'ls: non_existent_file: No such file or directory\n'

    There is an additional optional argument, "input", allowing you to
    pass a string to the subprocess's stdin.  If you use this argument
    you may not also use the Popen constructor's "stdin" argument, as
    it too will be used internally.  Example:

    >>> check_output(["sed", "-e", "s/foo/bar/"],
    ...              input=b"when in the course of fooman events\n")
    b'when in the course of barman events\n'

    If universal_newlines=True is passed, the "input" argument must be a
    string and the return value will be a string rather than bytes.
    """

subprocess.Popen(...)

>>> subprocess.Popen(["date"])
Fri Aug 18 17:25:22 CST 2017
<subprocess.Popen object at 0x7fdb3315b588> #开了新的内存空间执行
>>> 
>>> 
>>> subprocess.Popen("date",shell=True)
<subprocess.Popen object at 0x7fdb3315b358>
>>> Fri Aug 18 17:25:26 CST 2017

subprocess.Popen使用PIPE管道把数据存储到标准输入/标准输出/错误输出

import subprocess

res=subprocess.Popen(r'deeddddir D:\04\python1\day7\xml模块',
                     shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
print('=================>',res)
print('-========>',res.stdout.read())
print('-========>',res.stderr.read().decode('gbk'))
print('-========>',res.stderr.read().decode('gbk'))

#dir file_path | findstr xml$
res1=subprocess.Popen(r'dir D:\04\python\day7\xml模块',
                     shell=True,
                     stdout=subprocess.PIPE,)

# stdin=res1.stout
res2=subprocess.Popen(r'findstr xml$',
                     shell=True,
                     stdin=res1.stdout,
                     stdout=subprocess.PIPE,)

print(res2.stdout.read().decode('gbk'))

   官方说明

class Popen(object):
    """ Execute a child program in a new process.

    For a complete description of the arguments see the Python documentation.

    Arguments:
      args: A string, or a sequence of program arguments.

      bufsize: supplied as the buffering argument to the open() function when
          creating the stdin/stdout/stderr pipe file objects

      executable: A replacement program to execute.

      stdin, stdout and stderr: These specify the executed programs' standard
          input, standard output and standard error file handles, respectively.

      preexec_fn: (POSIX only) An object to be called in the child process
          just before the child is executed.

      close_fds: Controls closing or inheriting of file descriptors.

      shell: If true, the command will be executed through the shell.

      cwd: Sets the current directory before the child is executed.

      env: Defines the environment variables for the new process.

      universal_newlines: If true, use universal line endings for file
          objects stdin, stdout and stderr.

      startupinfo and creationflags (Windows only)

      restore_signals (POSIX only)

      start_new_session (POSIX only)

      pass_fds (POSIX only)

      encoding and errors: Text mode encoding and error handling to use for
          file objects stdin, stdout and stderr.

    Attributes:
        stdin, stdout, stderr, pid, returncode
View Code

XML模块

XML元素与HTML元素的格式基本相同,其格式如下:

<标记名称 属性名1="属性值1" 属性名1="属性值1" ……>内容</标记名称>

所有的数据内容都必须在某个标记的开始和结束标记内,而每个标记又必须包含在另一个标记的开始与结束标记内,形成嵌套式的分布,只有最外层的标记不必被其他的标记所包含。最外层的是根元素(Root),又称文件

(Document)元素,所有的元素都包含在根元素内。

a.xml举例:

#
<data>#根元素 <country a="1" name="Liechtenstein"> <rank updated="yes">2</rank> <year updated="yes" version="1.0">2010</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> <egon age="18">hello</egon> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year updated="yes" version="1.0">2013</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> <egon age="18">hello</egon></country> <country name="Panama"> <year updated="yes" version="1.0">2013</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> <egon age="18">hello</egon></country> </data>

常规操作演示:

import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()

for child in root:
    print('====>',child.tag)
    for i in child:
        print(i.tag,i.attrib,i.text)

# 查找element元素的三种方式
years=root.iter('year') #扫描整个xml文档树,找到所有
for i in years:
    print(i)

res1=root.find('country') #谁来调,就从谁下一层开始找,只找一个
print(res1)
#
res2=root.findall('country') #谁来调,就从谁下一层开始找,只找一个
print(res2)

#修改
years=root.iter('year') #扫描整个xml文档树,找到所有
for year in years:
    year.text=str(int(year.text)+1)
    year.set('updated','yes')
    year.set('version','1.0')
tree.write('a.xml')

#删除
for county in root.iter('country'):
    print(county.tag)
    rank=county.find('rank')
    if int(rank.text) > 10:
        county.remove(rank)
tree.write('a.xml')

#增加节点
for county in root.iter('country'):
    e=ET.Element('egon')
    e.text='hello'
    e.attrib={'age':'18'}
    county.append(e)

tree.write('a.xml')

   

posted @ 2017-08-18 08:14  warren1236  阅读(124)  评论(0)    收藏  举报