Python: Best/simplest way to read a config file?

Status
Not open for further replies.

danb35

Hall of Famer
Joined
Aug 16, 2011
Messages
15,504
Earlier this year, I took work from another user here and put together a Python script to automate deploying a Let's Encrypt certificate to a FreeNAS box using the API. For the sake of simplicity (and since I didn't really know how to do better), the configuration (hostname, username, password, etc.) is set directly in the script itself. That's not a very maintainable solution, though--users can't do a simple git pull to grab the most current version of the script, because their local copy doesn't match (any version of) what's in the repo.

One solution would be to specify these things as arguments on the command line, and I have a pull request submitted to do just that. It would make the script more maintainable/upgradable, but it would make it a bit of a pain to call it the way that I'd intended (i.e., as a deploy hook from the ACME client after the cert is issued). The solution I'd prefer would be to have the user prepare a config file setting the necessary variables, and have the script read that in.

With bash, this is simple--create a config file with lines like JAILS_PATH="/mnt/tank/jails/" and read it into the script with . /path/to/config. It may not be especially flexible, but I don't need the flexibility, and it's simple.

A bit of Googling for a Python solution, though, shows me a number of options, all of which seem more advanced than I really need. I see configparser and ConfigParser (apparently two different things), JSON, YAML, and others, but they all frankly look much more involved than what I'd need. Here's what I think I need:
  • Set about a half-dozen variables to static text values.
  • Be as simple as possible for me, a complete n00b in Python (if I even rise to the level of a n00b), to implement
  • Be as simple as possible for users to use--the fewer syntax requirements on the config file, the better. This, I think, argues against JSON as a solution
What suggestions would you have for something like this? Of what I've seen, I think I'm leaning toward configparser and its .ini-style files, but input from someone who knows Python better (which wouldn't be hard) would be appreciated.
 
Last edited:
Joined
Jul 10, 2016
Messages
521
Joined
Jul 10, 2016
Messages
521
Code:
import user_config

if "PASSWORD" not in dir(user_config):
	user_config.PASSWORD = "default password"
 

anmnz

Patron
Joined
Feb 17, 2018
Messages
286
'import' is a good solution. Just thought I'd add that the standard "ConfigParser" / "configparser" module is another popular and convenient choice, with some advantages.
 
Last edited:
Status
Not open for further replies.
Top