Python基础(14)_python模块之configparser模块、suprocess

9、configparser模块

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

常见的软件格式文档格式如下:

 1 [DEFAULT]
 2 ServerAliveInterval = 45
 3 Compression = yes
 4 CompressionLevel = 9
 5 ForwardX11 = yes
 6   
 7 [bitbucket.org]
 8 User = hg
 9   
10 [topsecret.server.com]
11 Port = 50022
12 ForwardX11 = no

使用configparser模块,创建格式文档:

import configparser

config=configparser.ConfigParser()

config['DEFAULT'] ={
    'ServerAliveInterval': '45',
     'Compression': 'yes',
     'CompressionLevel': '9',
     'ForwardX11':'yes'
}
config['bitbucket'] = {'User':'hg'}
config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
with open('config.ini','w',encoding='utf-8') as f:
    config.write(f)  

查找文件:以字典的方式

import configparser

config = configparser.ConfigParser()

#---------------------------查找文件内容,基于字典的形式

print(config.sections())        #  []

config.read('config.ini')     #读取文件

print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']

print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True


print(config['bitbucket.org']["user"])  # hg

print(config['DEFAULT']['Compression']) #yes

print(config['topsecret.server.com']['ForwardX11'])  #no


print(config['bitbucket.org'])          #<Section: bitbucket.org>

for key in config['bitbucket.org']:     # 注意,有default会默认default的键
    print(key)
>>user
     serveraliveinterval
     compression
     compressionlevel
     forwardx11

print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键
>>['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']

print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对
>>[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

print(config.get('bitbucket.org','compression')) # yes       get方法取深层嵌套的值
>>yes
     

增删改操作

import configparser

config = 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"))  

10、subprocess模块

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

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

简单命令:

a = subprocess.Popen('ls',shell=True)

windows中,创建子进程需要添加:shell=True

Linux中,创建子进程不需添加shell=True,在使用命令参数时需要添加shell=True

 

在创建Popen对象时,subprocess.PIPE可以初始化stdin, stdout或stderr参数。表示与子进程通信的标准流。

import subprocess
 
a = subprocess.Popen('ls',shell=True)       #  创建一个新的进程,与主进程不同步
print('>>>',a)                                   #a是Popen的一个实例对象
>>> <subprocess.Popen object at 0x0000024BB71BB128>

 #in Linux 系统中
subprocess.Popen('ls -l',shell=True)         #结果以字符串显示
 
subprocess.Popen(['ls','-l'])   #结果以列表显示

subprocess.PIPE

  在创建Popen对象时,subprocess.PIPE可以初始化stdin, stdout或stderr参数。表示与子进程通信的标准流。

import  subprocess
s=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)
print(s.stdout.read().decode('gbk'))

  subprocess创建了子进程,结果本在子进程中,if 想要执行结果转到主进程中,就得需要一个管道,即 : stdout=subprocess.PIPE

原文地址:https://www.cnblogs.com/hedeyong/p/7086025.html