Python:argparse可选参数,不带破折号 [英] Python: argparse optional arguments without dashes
问题描述
我想使用以下语法:
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.
编辑
我仍然不确定要在这里做什么,但是如果file1
和file2
是文字字符串,则可以通过预处理sys.argv
来解决该问题.当然,这仍然会奇怪地格式化您的帮助消息,但是您总是可以添加一个Epilog来说明两种形式都可以:
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屋!