Configparser module and Subprcess
Using the Configparser module to configure a file similar to the Windows.ini format can contain one or more sections (section), each of which can have multiple parameters (key = value).
Configured as such a file
[DEFAULT]
Serveraliveinterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[Bitbucket.org]
User = HG
[Topsecret.server.com]
Port = 50022
ForwardX11 = No
Using the Confiparser module in Python
Import Configparser
# Cfp=configparser. Configparser () # {}
# cfp["DEFAULT"]={"Serveraliveinterval": "Compression": "Yes", "CompressionLevel": 9, "ForwardX11": "Yes"}
# cfp["bitbucket.org"]={"USER": "HG"}
# cfp["topsecret.server.com"]={"Port": 5000123, "ForwardX11": "No"}
# with open ("Cfp.ini", "W") as F:
# Cfp.write (f)
Read the operation:
Import Configparser
Cfp=configparser. Configparser ()
Cfp.read ("Cfp.ini")
################################################
# Print (Cfp.sections ()) # Check the operation of the corresponding field
# print ("Topsecret.server.coms" in CFP)
For key in config[' bitbucket.org ': # Note that there is a key to default defaults
Print (key)
Print (config.options (' bitbucket.org ')) # with For loop, find all keys under ' bitbucket.org '
Print (Config.items (' bitbucket.org ')) #找到 all key-value pairs under ' bitbucket.org '
Print (Config.get (' bitbucket.org ', ' compression ')) # Yes Get method takes deep nested values
When we need to call the system's command, the first thing to consider is the OS module. Use Os.system () and Os.popen () to operate. However, these two commands are too simple to perform complex operations, such as providing input to a running command or reading the output of a command, judging the running state of the command, managing the parallelism of multiple commands, and so on. In this case, the Popen command in Subprocess will be able to perform the operation we need effectively.
Import subprocess
S=subprocess. Popen ("dir", shell=true,stdout=subprocess. PIPE) #在windos下必须得配置shell =true
Print (S.stdout.read (). Decode ("GBK"))
Under Linux:
Import subprocess
Subprocess. Popen (' ls-l ', shell=true)
Subprocess. Popen ([' ls ', '-l '])
Python basics-------Modules and Packages (iv)