Python optparse command line args

59 阅读2分钟

我在处理一个问题,需要从命令行运行具有不同参数的代码。我在网上找到了这个示例,但却找不到答案。我目前不在乎解析器错误,稍后我会处理,我只是对获得正确的参数感到困惑。 -l/--level INFO 是 设置日志级别为 DEBUG、INFO、WARNING、ERROR 和 CRITICAL -n/--name 如果为空则引发解析器错误 是 设置 Address 对象的 name 值 -a/--address 如果为空则引发解析器错误 是 设置 Address 对象的 street_address 值 -c/--city 如果为空则引发解析器错误 是 设置 Address 对象的 city 值 -s/--state 如果为空则引发解析器错误 是 设置 Address 对象的 state 值 -z/--zip_code 如果为空则引发解析器错误 是 设置 Address 对象的 zip_code 值

如果您使用以下命令行参数运行代码:

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

...您应该在 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

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.

2、解决方案

答案1:

从 options.level 获取 level 选项值并将其传递给 start_logging():

```python
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! 消息。

希望有所帮助。