常用模块-----configparser subprocess
生活随笔
收集整理的這篇文章主要介紹了
常用模块-----configparser subprocess
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 configparserconfig = 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) # 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模塊
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)?
?
轉載于:https://www.cnblogs.com/mona524/p/7086677.html
總結
以上是生活随笔為你收集整理的常用模块-----configparser subprocess的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中常用的并发工具类
- 下一篇: 项目管理系列之质量管理