I have created a python program that I will be compiling into an EXE but before that I want to have a command line switch that lets me specify the config file I want to use. My idea is to have multiple config files that server different purposes. I have searched the internet but am confused by what I am seeing. Any advice on how to do this would be greatly appreciated...
1 Answer
You should have a look at the argparse module, which handles command line options for you.
Edit: Let me give you a simple example.
import argparse
# create a new argument parser
parser = argparse.ArgumentParser(description="Simple argument parser")
# add a new command line option, call it '-c' and set its destination to 'config'
parser.add_argument("-c", action="store", dest="config_file")
# get the result
result = parser.parse_args()
# since we set 'config_file' as destination for the argument -c,
# we can fetch its value like this (and print it, for example):
print(result.config_file)
You can then proceed to use result.config_file as the file name of the config file passed to the script.
3 Comments
user3739525
thanks, I was looking at that but I am a huge newbie at this and I am a little confused by what I am seeing... If you could provide any additional insight it would be greatly appreciated... I will continue to try to figure it out...
user3739525
So if I understand what I am seeing I can import argparse parser = argparse.ArgumentParser parser.add_argument('-c', action="store", dest="config") config = ConfigParser.ConfigParser() config.readfp(open(config))
martineau
user3739525: Try it and see.