how to handle command line input options in python?
Question: I need a script which can take input via command line. Input will be a file
name and It will take a default input if no input is provided. The script will
also check the existence of the file.

Name of the script is : **wrapper.py**

input example :

    
    
    python wrapper.py -config abc.txt
    

my try:

    
    
    import argparse
    commandLineArgumentParser = argparse.ArgumentParser()
    commandLineArgumentParser.add_argument("-config", "--configfile", help="first Name")
    config = commandLineArguments.configfile
    


Answer: You should put you code which loads configuration into a function. Then you
should pass file name to it and return all configuration data.

So, start with:

    
    
    def read_configuration_from_file(filename):
        config_parser = ConfigParser.ConfigParser()
        config_parser.read(filename)
    

Once you read information from config_parser, you have to figure out how to
return the configuration. There are many options. You could return a
dictionary, or you could create your own object which contains configuration.

Option 1 (dictionary):

    
    
    return {'first_name': first_name, 'last_name': last_name}
    

Option 2 (configuration data class):

    
    
    class ConfigurationData(object):
        def __init__(self, first_name, last_name):
            self.first_name = first_name
            self.last_name = last_name
    

and then you just `return ConfigurationData(first_name=first_name,
last_name=last_name)`.

You can also merge it all and make the _read_ function part of the class:

    
    
    class ConfigurationData(object):
        def __init__(self, first_name, last_name):
            self.first_name = first_name
            self.last_name = last_name
    
        @staticmethod
        def read_configuration_from_file(filename):
            config_parser = ConfigParser.ConfigParser()
            config_parser.read(filename)
            ...
            return ConfigurationData(first_name=first_name, last_name=last_name)
    

