A configuration file that can be read by python and shell

Question:

I have python scripts and shell scripts in the same folder which both need configuration. I currently have a config.py for my python scripts but I was wondering if it is possible to have a single configuration file which can be easily read by both python scripts and also shell scripts.

Can anyone give an example of the format of a configuration file best suited to being read by both python and shell.

Asked By: Jimmy

||

Answers:

I think the simplest solution will be :

key1="value1"
key2="value2"
key3="value3"

in you just have to source this env file and in Python, it’s easy to parse.

Spaces are not allowed around =

For Python, see this post : Emulating Bash 'source' in Python

Answered By: Gilles Quénot

This is valid in both shell and python:

NUMBER=42
STRING="Hello there"

what else do you need?

Answered By: Emanuele Paolini

configobj, a third party library you can install with pip can help with this.

from configobj import ConfigObj
cfg = ConfigObj('/home/.aws/config')
access_key_id = cfg['aws_access_key_id']
secret_access_key = cfg['aws_secret_access_key']

Configobj’s homepage: https://github.com/DiffSK/configobj

Answered By: Ilja

Keeping “config.py” rather than “config.sh” leads to some pretty code.

config.py

CONFIG_VAR = "value"
CONFIG_VAR2 = "value2"

script.py:

import config

CONFIG_VAR = config.CONFIG_VAR
CONFIG_VAR2 = config.CONFIG_VAR2

script.sh:

CONFIG_VAR="$(python-c 'import config;print(config.CONFIG_VAR)')"
CONFIG_VAR2="$(python-c 'import config;print(config.CONFIG_VAR2)')"

Plus, this is a lot more legible than trying to “Emulate Bash ‘source’ in Python” like Gilles answer requires.

Answered By: AlexPogue