我有一个关于在 Python 中传递参数的问题。例如:在脚本中我期待这样的参数
1.python run.py -create vairbale1 -reference variable2 many more variables
2.python run.py -get -list variable many more variable
我如何在脚本中使用 optparse 或 getopt 来执行此操作,如果参数无效,我需要打印无效参数
from optparse import OptionParser
parser = OptionParser()
最佳答案
这是我使用过的一个片段。我为我工作,尽管您可能必须更改参数类型。
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)
关于Python 解析来自命令行的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9923168/