[英]Python optparse command line 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”,然后運行腳本,如何將日志級別設置為警告此級別。 我還需要致電-n Tom等。我不需要arg的答案,而只是對它如何工作的一般了解。 我也不擔心現在的解析錯誤,只是能夠正確設置參數。
從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!
日志文件中的消息。
希望能有所幫助。
optparse已過時,應使用argparse
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.