Python:没有破折号的 argparse 可选参数 [英] Python: argparse optional arguments without dashes

查看:33
本文介绍了Python:没有破折号的 argparse 可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要以下语法:

python utility.py file1 FILE1 file2 FILE2

其中 file1 和 file2 是可选参数.使用这种语法很简单:

where file1 and file2 are optional arguments. It is simple to make it working with this syntax:

python utility.py --file1 FILE1 --file2 FILE2

使用

parser.add_argument('--file1',type=file)
parser.add_argument('--file2',type=file)

但是,如果我删除破折号,argparse 开始将其解释为位置参数而不是可选参数...

however, if I remove the dashes, argparse starts to interprete it as a positional rather than optional argument...

换句话说,是否可以明确地告诉 argparse 一个参数是可选的还是位置的,这样我就可以有没有破折号的可选参数?

In other words, is it possible to specifically tell argparse whether an argument is optional or positional so that I can have optional parameters without the dashes?

推荐答案

没有办法让 argparse 为你做这件事.但是,您可以让 argparse 接受任意数量的位置参数:

There is no way to get argparse to do this for you. However, you can make argparse accept any number of positional arguments:

parser.add_argument('FILES',nargs='*')
options=parser.parse_args()
file1,optional_files=options.FILES[0],options.FILES[1:]

当然,您可能需要添加一些检查以确保至少提供了 1 个文件等.

Of course, you may want to add some checks to make sure that at least 1 file was given, etc.

编辑

我仍然不能 100% 确定您在这里想要什么,但是如果 file1file2 是文字字符串,您可以通过预处理来解决这个问题 <代码>sys.argv.当然,这仍然会奇怪地格式化您的帮助消息,但您始终可以添加一个结语,说明任何一种形式都可以:

I'm still not 100% sure what you want here, but if file1 and file2 are literal strings, you can work around that a little bit by preprocessing sys.argv. Of course, this will still format your help message strangely, but you can always add an epilog explaining that either form is OK:

import argparse
import sys

mangle_args=('file1','file2')
arguments=['--'+arg if arg in mangle_args else arg for arg in sys.argv[1:]]

parser=argparse.ArgumentParser()
parser.add_argument('--file1')
parser.add_argument('--file2')
options=parser.parse_args(arguments)

这篇关于Python:没有破折号的 argparse 可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆