Python 解析来自命令行的参数

标签 python

我有一个关于在 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/

相关文章:

python - 交叉熵 Keras 中的自定义参数

python - 安塞 bool + 10.11.6

python - 简化 shell 脚本中 python 测试的执行

python - 不知道如何摆脱列表中的这些 {} (python2.7)

python - 从 Python 将 TFRecord 输出到 Google Cloud Storage

python - 使用索引和名称列重命名索引

python - Revit API 2015 Python : GetAllViewports() takes exactly 1 argument (0 given)

python - Python 中将元素添加到逗号分隔字符串的有效方法

python - 如何让 httpretty 在测试期间停止打印异常?

python - 下一个回文数