是否可以使用argparse来捕获任意一组可选参数?
16lz
2021-01-22
Is it possible to use argparse
to capture an arbitrary set of optional arguments?
是否可以使用argparse来捕获任意一组可选参数?
For example both the following should be accepted as inputs:
例如,下列两项应被接受为输入:
python script.py required_arg1 --var1 value1 --var2 value2 --var3 value3
python script.py required_arg1 --varA valueA --var2 value2 --varB valueB
a priori I don't know what optional arguments would be specified receive but would handle them accordingly.
事先我不知道会指定哪些可选参数接收,但会相应地处理它们。
2 个解决方案
#1
11
This is kind of a hackish way, but it works very well:
这是一种陈腐的方法,但效果很好:
Check, which arguments are not added and add them
检查,哪些参数没有添加并添加
parser=argparse.ArgumentParser()
parser.add_argument("foo")
parser.add_argument("-bar", type=int)
#parser can have any arguments, whatever you want!
parsed, unknown = parser.parse_known_args() #this is an 'internal' method
# which returns 'parsed', the same as what parse_args() would return
# and 'unknown', the remainder of that
# the difference to parse_args() is that it does not exit when it finds redundant arguments
for arg in unknown:
if arg.startswith(("-", "--")):
#you can pass any arguments to add_argument
parser.add_argument(arg, type=<your type>, ...)
args=parser.parse_args()
For example:
例如:
python arbitrary_parser.py ha -bar 12 -lol huhu -rofl haha
Then the result would be
那么结果就是
args = Namespace(bar=12, foo='ha', lol='huhu', rofl='haha')
更多相关文章
- jira python oauth:如何获取身份验证的参数?
- Python——函数 8、可变长参数
- python函数不定长参数
- 关于Python的属性、参数、方法的解释、区别
- Django反向url与参数到基于类的视图
- 无法安装ndg-httpsclient或者我的解决方案错误
- shell用户配置详解及bash命令参数
- linux 下命令行传参数问题
- Linux无法连接网络解决方案