这是我用过的一个片段。我为我工作,但您可能需要更改参数类型。
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)
FYI自定义操作:'optparse'模块现在已经贬值。从2.7开始,你可能会想要使用'argparse'模块:http://docs.python.org/library/argparse.html#module-argparse – 2012-03-29 10:12:47