Librería configparser (lenguaje de configuración básico)#
Última modificación: Mayo 14, 2022
Ejemplo de un archivo de configuración#
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
Creación desde Python#
[1]:
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {
"ServerAliveInterval": "45",
"Compression": "yes",
"CompressionLevel": "9",
}
config["bitbucket.org"] = {}
config["bitbucket.org"]["User"] = "hg"
config["topsecret.server.com"] = {}
topsecret = config["topsecret.server.com"]
topsecret["Port"] = "50022" # mutates the parser
topsecret["ForwardX11"] = "no" # same here
config["DEFAULT"]["ForwardX11"] = "yes"
with open("/tmp/example.ini", "w") as configfile:
config.write(configfile)
[2]:
!cat /tmp/example.ini
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
port = 50022
forwardx11 = no
Lectura desde Python#
[3]:
#
# Crea una instancia de ConfigParser()
#
config = configparser.ConfigParser()
[4]:
#
# Lista las secciones
#
config.sections()
[4]:
[]
[5]:
#
# Lee el archivo
#
config.read('/tmp/example.ini')
[5]:
['/tmp/example.ini']
[6]:
#
# Lista la secciones
#
config.sections()
[6]:
['bitbucket.org', 'topsecret.server.com']
[7]:
#
# Condicional sobre una sección
#
'bitbucket.org' in config
[7]:
True
[8]:
'bytebong.com' in config
[8]:
False
[9]:
#
# Extrae el valor de un parámetro de una sección
#
config['bitbucket.org']['User']
[9]:
'hg'
[10]:
#
# Extracción de un valor de la sección DEFAULT
#
config['DEFAULT']['Compression']
[10]:
'yes'
[11]:
#
# Carga una sección a una variable
#
topsecret = config['topsecret.server.com']
topsecret['ForwardX11']
[11]:
'no'
[12]:
topsecret['Port']
[12]:
'50022'
[13]:
#
# Itaración sobre una seccción
#
for key in config['bitbucket.org']:
print(key)
user
serveraliveinterval
compression
compressionlevel
forwardx11
[14]:
#
# Extracción de un valor de una sección de usuario
#
config['bitbucket.org']['ForwardX11']
[14]:
'yes'
Fallback#
[15]:
'BatchMode' in config
[15]:
False
[16]:
config.getboolean('BatchMode', fallback=True, option='xxx')
[16]:
True
[17]:
config['DEFAULT']['BatchMode'] = 'no'
topsecret.getboolean('BatchMode', fallback=True)
[17]:
False