Trying_hard
Trying_hard

Reputation: 9501

Python optparse command line args

I am working on a problem I need to run with different args from a command line. I found this example online but no answer. I am not currently not worried about the parser errors, I can do that later, I am just stumped on getting the args right.

-l/--level INFO yes Sets the log level to DEBUG, INFO, WARNING, ERROR, and CRITICAL 
-n/--name Throws a parser error if empty yes Sets the name value of the Address object 
-a/--address Throws a parser error if empty yes Sets the street_address value of the Address object 
-c/--city Throws a parser error if empty yes Sets the city value of the Address object 
-s/--state Throws a parser error if empty yes Sets the state value of the Address object 
-z/--zip_code Throws a parser error if empty yes Sets the zip_code value of the Address object 

If you run your code with the following command-line arguments:

property_address.py -n Tom -a "my street" -c "San Diego" -s "CA" -z 21045

...you should see something like this in property_address.log:

2010-10-11 14:48:59,794 - INFO - __init__ - Creating a new address 

I have the following code for this:

import re

import logging

LOG_FILENAME = "property_address.log"
LOG_FORMAT = "%(asctime)s-%(levelname)s-%(funcName)s-%(message)s"
DEFAULT_LOG_LEVEL = "error" # Default log level
LEVELS = {'debug': logging.DEBUG,
          'info': logging.INFO,
          'warning': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL
         }

def start_logging(filename=LOG_FILENAME, level=DEFAULT_LOG_LEVEL):
    "Start logging with given filename and level."
    logging.basicConfig(filename=filename, level=LEVELS[level],format=LOG_FORMAT)
    # log a message
    logging.info('Starting up the property_address program')

class StateError(Exception): pass

class ZipCodeError(Exception):pass

class Address(object):

    states = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN', 
              'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL', 'TN', 
              'MA', 'OH', 'MD', 'MI', 'WY', 'WA', 'OR', 'MH', 'SC', 'IN', 'LA', 'MP', 'DC', 'MT', 'AR', 'WV', 'TX']


    def __init__(self,name, street_address, city, state, zip_code):
        self._name = name
        logging.info('Creating a new name')
        self._street_address = street_address
        logging.info('Creating a new address')
        self._city = city
        logging.info('Creating a new city')
        self._state = state
        logging.info('Creating a new state')
        self._zip_code = zip_code
        logging.info('Creating a new zip_code')


    @property
    def name(self):
        return self._name.title()

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self,value):
        if value not in self.states:
            logging.error('STATE exception')
            raise StateError(value)

        self._state = value
        logging.info('Creating a new state')

    @property
    def zip_code(self):
        return self._zip_code

    @zip_code.setter
    def zip_code(self,value):
        if re.match(r"^\d\d\d\d\d$",value):
            self._zip_code = value
            logging.info('Creating a new ZipCode')
        else:
            logging.error('ZIPCODE exception')
            raise ZipCodeError

I am having trouble with setting up the args. I am currently trying:

if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option('-l', '--level', dest="level", action="store", 
                            help="sets level")

    (options, args) = parser.parse_args()

How can I set the log level to warning this if I run "-l warning" from the command line, and then run the script. I also need to call -n Tom etc. I don't need the answer to ever arg, just a general understanding of how this would work. I am alos not worried about the parse errors now, just being able to get the args right.

Upvotes: 0

Views: 389

Answers (2)

jesjimher
jesjimher

Reputation: 1245

optparse is deprecated, you should use argparse

Upvotes: 0

alecxe
alecxe

Reputation: 474201

Get the level option value from options.level and pass it to start_logging():

if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option('-l', '--level', dest="level", action="store",
                            help="sets level")

    (options, args) = parser.parse_args()
    start_logging(level=options.level)

    logging.error('ERROR!')
    logging.info('INFO')

After running the script with -l warning, there is only ERROR! message written to the log file.

If you run it with -l info, you would see both ERROR! and INFO! messages in the log file.

Hope that helps.

Upvotes: 1

Related Questions