Argparse有一个参数的两个值

suv*_*rev 7 python command-line argparse

现在我的脚本调用:

python resylter.py -n *newfile* -o *oldfile*
Run Code Online (Sandbox Code Playgroud)

代码看起来像:

parser.add_argument('-n', '--newfile', help='Uses only with -o argument. Compares inputed OLD (-o) file with previous run results with NEW(-n) output.xml file with actual run results')
parser.add_argument('-o', '--oldfile', help='Uses only with -n argument. Compares inputed OLD (-o)  file with previous run results with NEW(-n) output.xml file with actual run results')
Run Code Online (Sandbox Code Playgroud)

和一些行动

如何编辑它才能像这样使用?:

python resylter.py -n *newfile* *oldfile*
Run Code Online (Sandbox Code Playgroud)

sys.argv [-1]没有用

wja*_*rea 13

回答OP的回答:

星号nargs='*'表示零个或多个参数(如正则表达式),在此上下文中没有意义.你想要的nargs=2.

parser.add_argument(
    '-c',
    '--compare',
    nargs=2,
    metavar=('newfile', 'oldfile'),
    help='Compares previous run results in oldfile with actual run results in newfile.',
    )

args = parser.parse_args()

newfile, oldfile = args.compare
Run Code Online (Sandbox Code Playgroud)

metavar=('newfile', 'oldfile')如果运行,还可以添加帮助文本resylter.py -h.


suv*_*rev 0

工作与nargs = '*'

我做了以下操作:

parser.add_argument('-c', '--compare', nargs = '*')

_newfile_ = _args_.compare[0]
_oldfile_ = _args_.compare[1]
Run Code Online (Sandbox Code Playgroud)

现在可以了