Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A configuration file that can be read by python and shell

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.

like image 959
Jimmy Avatar asked Jan 21 '13 15:01

Jimmy


People also ask

What is the configuration file for shell?

Use of external configuration files prevents a user from making changes to a script. Config file is added with the help of source command. If a script is shared in many users and every user need a different configuration file, then instead of changing the script each time simply include the config files.

What are configuration files in Python?

Config files are used to store key value pairs or some configurable information that could be read or accessed in the code and at some point, of time.

Does Python have a config file?

Python can have config files with all settings needed by the application dynamically or periodically. Python config files have the extension as . ini. We'll use VS Code (Visual Studio Code) to create a main method that uses config file to read the configurations and then print on the console.


2 Answers

I think the simplest solution will be :

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

in shell 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

like image 67
Gilles Quenot Avatar answered Nov 12 '22 07:11

Gilles Quenot


configobj lib 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']
like image 33
Ilja Avatar answered Nov 12 '22 06:11

Ilja