1. 程式人生 > >Day26:configparser、subprocess模塊

Day26:configparser、subprocess模塊

host wait方法 add 流控 with 操作 rem 復雜 python

一、configparser模塊

該模塊適用於配置文件的格式與windows ini文件類似,可以包含一個或多個節(section),每個節可以有多個參數(鍵=值)。

1、創建文件

一般軟件的常見文檔格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no

使用Python來生成這樣的文件

import
configparser config = 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)

2、查找文件

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方法取深層嵌套的值

3、增刪改操作

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模塊

當我們需要調用系統的命令的時候,最先考慮的os模塊。用os.system()和os.popen()來進行操作。但是這兩個命令過於簡單,不能完成一些復雜的操作,如給運行的命令提供輸入或者讀取命令的輸出,判斷該命令的運行狀態,管理多個命令的並行等等。這時subprocess中的Popen命令就能有效的完成我們需要的操作。

subprocess模塊允許一個進程創建一個新的子進程,通過管道連接到子進程的stdin/stdout/stderr,獲取子進程的返回值等操作。

The subprocess module 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。

1、簡單命令

import subprocess

#  創建一個新的進程,與主進程不同步  if in win: s=subprocess.Popen(‘dir‘,shell=True)
s=subprocess.Popen(ls)
s.wait()                  # s是Popen的一個實例對象

print(ending...)

2、命令帶參數

linux:

import subprocess

subprocess.Popen(ls -l,shell=True)

#subprocess.Popen([‘ls‘,‘-l‘])  

3、控制子進程

當我們想要更個性化我們的需求的時候,就要轉向Popen類,該類生成的對象用來代表子進程。剛才我們使用到了一個wait方法

此外,你還可以在父進程中對子進程進行其它操作:

s.poll() # 檢查子進程狀態
s.kill() # 終止子進程
s.send_signal() # 向子進程發送信號
s.terminate() # 終止子進程

s.pid:子進程號

4、子進程的文本流控制

可以在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對象的一個方法,該方法會阻塞父進程,直到子進程完成

5、快捷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…來檢查。


‘‘‘

Day26:configparser、subprocess模塊