python(十六),,一、 configp


一、 configparser模块

该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

创建文件

来看一个好多软件的常见文档格式如下:

技术分享
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes  [bitbucket.org]User = hg  [topsecret.server.com]Port = 50022ForwardX11 = no
技术分享

如果想用python生成一个这样的文档怎么做呢?

技术分享
import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,                      ‘Compression‘: ‘yes‘,                     ‘CompressionLevel‘: ‘9‘,                     ‘ForwardX11‘:‘yes‘                     }config[‘bitbucket.org‘] = {‘User‘:‘hg‘}config[‘topsecret.server.com‘] = {‘Host Port‘:‘50022‘,‘ForwardX11‘:‘no‘}with open(‘example.ini‘, ‘w‘) as configfile:   config.write(configfile)
技术分享

查找文件

技术分享
import configparserconfig = configparser.ConfigParser()#---------------------------查找文件内容,基于字典的形式print(config.sections())        #  []config.read(‘example.ini‘)print(config.sections())        #   [‘bitbucket.org‘, ‘topsecret.server.com‘]print(‘bytebong.com‘ in config) # Falseprint(‘bitbucket.org‘ in config) # Trueprint(config[‘bitbucket.org‘]["user"])  # hgprint(config[‘DEFAULT‘][‘Compression‘]) #yesprint(config[‘topsecret.server.com‘][‘ForwardX11‘])  #noprint(config[‘bitbucket.org‘])          #<Section: bitbucket.org>for key in config[‘bitbucket.org‘]:     # 注意,有default会默认default的键    print(key)print(config.options(‘bitbucket.org‘))  # 同for循环,找到‘bitbucket.org‘下所有键print(config.items(‘bitbucket.org‘))    #找到‘bitbucket.org‘下所有键值对print(config.get(‘bitbucket.org‘,‘compression‘)) # yes       get方法取深层嵌套的值
技术分享

增删改操作

技术分享
import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)config.add_section(‘yuan‘)config.remove_section(‘bitbucket.org‘)config.remove_option(‘topsecret.server.com‘,"forwardx11")config.set(‘topsecret.server.com‘,‘k1‘,‘11111‘)config.set(‘yuan‘,‘k2‘,‘22222‘)config.write(open(‘new2.ini‘, "w"))
技术分享

二、 subprocess模块

当我们需要调用系统的命令的时候,最先考虑的os模块。用os.system()和os.popen()来进行操作。但是这两个命令过于简单,不能完成一些复杂的操作,如给运行的命令提供输入或者读取命令的输出,判断该命令的运行状态,管理多个命令的并行等等。这时subprocess中的Popen命令就能有效的完成我们需要的操作。

subprocess模块允许一个进程创建一个新的子进程,通过管道连接到子进程的stdin/stdout/stderr,获取子进程的返回值等操作。

The subprocessmodule allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

This module intends to replace several other, older modules and functions, such as: os.system、os.spawn*、os.popen*、popen2.*、commands.*

这个模块只一个类:Popen。

简单命令

技术分享
import subprocess#  创建一个新的进程,与主进程不同步  if in win: s=subprocess.Popen(‘dir‘,shell=True)s=subprocess.Popen(‘ls‘)s.wait()                  # s是Popen的一个实例对象print(‘ending...‘)     
技术分享

命令带参数

linux:
import subprocesssubprocess.Popen(‘ls -l‘,shell=True)#subprocess.Popen([‘ls‘,‘-l‘])

控制子进程

当我们想要更个性化我们的需求的时候,就要转向Popen类,该类生成的对象用来代表子进程。刚才我们使用到了一个wait方法

此外,你还可以在父进程中对子进程进行其它操作:

s.poll() # 检查子进程状态s.kill() # 终止子进程s.send_signal() # 向子进程发送信号s.terminate() # 终止子进程s.pid:子进程号

子进程的文本流控制

可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):

技术分享
import subprocess# s1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)# print(s1.stdout.read())#s2.communicate()s1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)s2 = subprocess.Popen(["grep","0:0"],stdin=s1.stdout, stdout=subprocess.PIPE)out = s2.communicate()print(out)
技术分享

ubprocess.PIPE实际上为文本流提供一个缓存区。s1的stdout将文本输出到缓存区,随后s2的stdin从该PIPE中将文本读取走。s2的输出文本也被存放在PIPE中,直到communicate()方法从PIPE中读取出PIPE中的文本。
注意:communicate()是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成

快捷API

技术分享
‘‘‘subprocess.call()父进程等待子进程完成返回退出信息(returncode,相当于Linux exit code)subprocess.check_call()父进程等待子进程完成返回0,检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try…except…来检查subprocess.check_output()父进程等待子进程完成返回子进程向标准输出的输出结果检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try…except…来检查。‘‘‘

python(十六)

评论关闭