我现在开始探索Python,并且正在测试如何使用“ argparse”将参数传递给脚本。
我编写示例脚本的方式如下,其中通过标志-i和-o传递的参数是强制性的,而标志-u是可选的:

#!/usr/bin/python

import sys
import argparse

## set usage options and define arguments
usage = "usage: %prog [options]"
parser = argparse.ArgumentParser(usage)

parser.add_argument("-i",  action="store", dest="input", help="input file")
parser.add_argument("-o",  action="store", dest="output", help="output file")
parser.add_argument("-u", action="store_true", dest="isunfolded", default=False, help="optional flag")

args = parser.parse_args()

print len(sys.argv)
if len(sys.argv) < 2:
#        parser.print_help()
        print 'Incorrect number of params'
        exit()
else:
        print "Correct number of params: ", len(sys.argv)


运行此脚本:

> ./test-args.py -i a -o b


印刷品:

5
Correct number of params:  5


我理解if条件(5大于2)中的打印语句,但是,在阅读argparse文档(https://docs.python.org/3/library/argparse.html)之后,我仍然不太明白为什么-i和-o标志被视为参数。这种行为似乎与例如perl Getopt :: Std,我更习惯了。

因此,问题是在Python中解析参数并评估强制参数是否存在的最佳方法是什么(不使用required = True)

最佳答案

它给您5,因为sys.argv包含作为参数传递给python的原始输入(脚本名称和4个参数)。

您可以将argparse视为对此的抽象,因此一旦使用它,就可以忘记sys.argv。在大多数情况下,最好不要混合使用这两种方法。

argparse是处理参数的一种好方法,我不完全理解为什么您不愿意使用required选项。另一种选择是自己解析sys.argv(也许是正则表达式?),然后完全删除argparse

关于python - 了解Python中用argparse进行参数解析,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27806340/

10-09 20:14
查看更多