Last active
March 14, 2018 20:37
-
-
Save TaDahCorp/90c6f5ea41860cd8681bccfc4aacdb29 to your computer and use it in GitHub Desktop.
Using ConfigParser as an alternative to argparse in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Personalized] | |
# ------------------------------------ | |
# Sample Configuration | |
# ------------------------------------ | |
# Do NOT delete any line | |
# File is required for [name].py to function | |
# | |
# IP | |
IP=192.168.10.227 | |
# max amount storage. | |
max_storage = 13.5 | |
[Account] | |
# Enter values below or NA | |
account_sid = ABC123 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ConfigParser | |
# load external configuration settings | |
configParser = ConfigParser.RawConfigParser() | |
configFilePath = r'config.txt' | |
try: | |
configParser.read(configFilePath) | |
max_storage = float(configParser.get('Personalized', 'max_storage')) | |
my_IP = configParser.get('Personalized', 'IP') | |
print("Configuration settings read correctly. IP:",my_IP," Capacity: ", max_storage) | |
except ConfigParser.Error: | |
print("Incorrect or missing config.txt file. Aborting") | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
argparse is a great option when the parameters change every time the Python code is invoked. But it is a bit complicated to program (lots of options) and not forgiving at runtime for a novice user, in particular if there are a lot of parameters required.
ConfigParser (installed via pip, for instance) uses a plain text file that most users will know how to edit.
The example above highlights how to use ConfigParser. For example to define the IP of a device or a storage limitation.
In some cases you will need both, ConfigParser for what remains mostly the same and argparse for last-minute runtime changes, for example choosing between various execution modes of the same Python script (receive, send, status, etc.)