Python optparse命令行参数

时间:2014-03-26 15:58:47

标签: python

我正在处理一个问题,我需要在命令行中使用不同的args运行。我在网上找到了这个例子,但没有答案。我目前并不担心解析器错误,我可以在以后做到这一点,我只是难以让args正确。

-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 

我有以下代码:

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

我在设置args时遇到了麻烦。我正在尝试:

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

    (options, args) = parser.parse_args()

如果我运行" -l warning"如何设置日志级别以警告此情况?从命令行,然后运行该脚本。我还需要打电话给汤姆等。我不需要答案,只需要大致了解这是如何工作的。我现在也不担心解析错误,只是能够正确使用args。

2 个答案:

答案 0 :(得分:1)

options.level获取级别选项值,并将其传递给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')

使用-l warning运行脚本后,只有ERROR!消息写入日志文件。

如果您使用-l info运行它,您会在日志文件中看到ERROR!INFO!条消息。

希望有所帮助。

答案 1 :(得分:0)

不推荐使用optparse,您应该使用argparse