ここに私が使ったスニペットがあります。私は私のために働いたが、パラメータタイプを変更する必要があるかもしれない。あなたは
import argparse
import re
class ValidateEmailAction(argparse.Action):
'''
Function will not validate domain names.
e.g. [email protected] is valid here.
'''
def __call__(self, parser, namespace, values, option_string=None):
super(argparse.Action, self).__call__(parser, namespace, values,
option_string=option_string)
email = values
pattern = "^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$"
if not re.match(pattern, email) != None:
raise AttributeError
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--email', action=ValidateEmailAction, help='Enter valid email.')
のようなあなたのデータを検証するカスタムアクションを使用することができます
parser = OptionParser()
parser.add_option('-n', '--db_name', help='DB Name (comma separated if multiple DBs - no spaces)')
parser.add_option('-H', '--db_host', help='DB host (comma separated if multiple DBs - no spaces)')
parser.add_option('-p', '--db_port', help='DB port (optional)')
parser.add_option('-u', '--db_user', help='DB user')
parser.add_option('-w', '--db_pass', help='DB password')
parser.add_option('-o', '--output-file', help='output file')
options, args = parser.parse_args()
errors = []
error_msg = 'No %s specified. Use option %s'
if not options.db_name:
errors.append(error_msg % ('database name', '-n'))
if not options.db_host:
errors.append(error_msg % ('database host', '-H'))
if not options.db_user:
errors.append(error_msg % ('database user', '-u'))
if not options.db_pass:
errors.append(error_msg % ('database password', '-w'))
if not options.output_file:
errors.append(error_msg % ('output file', '-o'))
if errors:
print '\n'.join(errors)
sys.exit(1)
上のカスタムアクションを確認してください: 'optparse'モジュールは、減価償却されています。 2.7の時点で、おそらく 'argparse'モジュールを使いたいと思うでしょう:http://docs.python.org/library/argparse.html#module-argparse –