码迷,mamicode.com
首页 > 其他好文 > 详细

常用模块-----configparser & subprocess

时间:2017-06-27 19:59:25      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:mmu   level   进程创建   操作文件   default   []   print   nic   end   

configparser 模块

功能:操作模块类的文件,configparser类型文件的操作类似于字典,大多数用法和字典相同。

新建文件:

import configparser
cfg=configparser.ConfigParser()
cfg[DEFAULT]={ServerAliveInterval: 45,
                      Compression: yes,
                     CompressionLevel: 9,
                     ForwardX11:yes
                     }
cfg[bitbucket.org]={User:hg}
cfg[topsecret.server.com]={host port:50022,Forwardx11:no}
with open(cfg.int,w) as f:
    cfg.write(f)
#DEFAULT 关键字,是默认参数,将DEFAULT 里的内容(value)匹配给每个自定义模块,比如:bitbucket.org

 cfg.int 文件内容如下:

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no

操作文件内容
import configparser

config = configparser.ConfigParser()

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

print(config.sections())        #  []

config.read(example.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)

print(config.options(bitbucket.org))  # 同for循环,找到‘bitbucket.org‘下所有键

print(config.items(bitbucket.org))    #找到‘bitbucket.org‘下所有键值对

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

增删改操作

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

subprocess模块

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

import subprocess

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

print(ending...)     

子进程文本控制流

可以在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)

 



 

常用模块-----configparser & subprocess

标签:mmu   level   进程创建   操作文件   default   []   print   nic   end   

原文地址:http://www.cnblogs.com/mona524/p/7086677.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!