1. 程式人生 > >Python基礎之常用模塊(三)

Python基礎之常用模塊(三)

section signal server .section 通過 sub 實例 wait 配置文件

1.configparser模塊

該模塊是用來對文件進行讀寫操作,適用於格式與Windows ini 文件類似的文件,可以包含一個或多個節(section),每個節可以有多個參數(鍵值對)

配置文件的格式如下:

[DEFAULT]
serveralagas = 24
asdgasg = yes
sdg = 123

[hello]
user = hd

[world]
what = fuck

 這種文件格式就像是一個大字典,每個標題就是一個key,字典中嵌套著字典

  還有需要註意的是,[DEFAULT]中的鍵值對是公用的,[DEFAULT]可以不寫

怎樣由Python中寫入這樣一個文件呢?

import configparser

cfp=configparser.ConfigParser()  #就是一個空字典

cfp[DEFAULT]={"serveralagas":24,"asdgasg":yes,"sdg":123}

cfp[hello]={user:hd}

cfp[world]={what:fuck}

with open(cfp.ini,w)as f:
    cfp.write(f)

讀取文件內容

#讀取文件

import configparser

config=configparser.ConfigParser()
config.read(
cfp.ini) #查看所有標題 res=config.sections() print(res) #[‘hello‘, ‘world‘] #查看標題hello下的所有鍵值對的key options=config.options(hello) print(options) #[‘user‘, ‘serveralagas‘, ‘asdgasg‘, ‘sdg‘] #查看標題hello下的所有鍵值對的(key,value) 格式 item_list=config.items(hello) print(item_list) #[(‘serveralagas‘, ‘24‘), (‘asdgasg‘, ‘yes‘), (‘sdg‘, ‘123‘), (‘user‘, ‘hd‘)]
#以字符串的形式查看hello標題下user的值 val=config.get(hello,user) print(val) #hd #上面那條命令,get可以改成getint,查看整數格式,改成getboolean,查看布爾值格式 #改成getfloat查看浮點型格式

修改文件內容

import configparser

config=configparser.ConfigParser()
config.read(cfp.ini)

#刪除整個標題hello
config.remove_section(hello)

#刪除標題world下的what
config.remove_option(world,what)

#判段是否存在某個標題
print(config.has_section(hello))

#判斷標題world下是否有user
print(config.has_option(world,user))

#添加一個標題
config.add_section(zhang)  #如果已經存在則會報錯

#在標題下添加name=zhang,age=18的配置
config.set(zhang,name,zhang)
config.set(zhang,age,18)#會報錯,TypeError: option values must be strings
                            # 必須是字符串形式

#將修改後的內容寫入文件,完成最後的修改
config.write(open(cfp.ini,w))

2.subprocess模塊

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

這個模塊只有一個Popen類

import subprocess

#創建一個新的進程,與主進程不同步s=subprocess.Popen(‘dir‘,shell=True)
#s是Popen的一個實例化對象s.wait()  #手動控制子進程的執行稍後一點print(‘ending‘)  #主進程的命令
#當然在父進程中還可以對子進程有更多的操作
s.poll()    #查看子進程的狀態
s.kill()    #終止子進程
s.send_signal()#向子進程發送信號
s.terminate() #終止子進程

還可以在Popen()建立子進程的時候改變標準輸入、標準輸出和標準錯誤,並用subprocess.PIPE將多個子進程的輸入輸出連接在一起,構成管道

import subprocess

s1=subprocess.Popen([ls,-l],stdout=subprocess.PIPE)
print(s1.stdout.read())

Python基礎之常用模塊(三)