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')

更多相关文章

  1. jira python oauth:如何获取身份验证的参数?
  2. Python——函数 8、可变长参数
  3. python函数不定长参数
  4. 关于Python的属性、参数、方法的解释、区别
  5. Django反向url与参数到基于类的视图
  6. 无法安装ndg-httpsclient或者我的解决方案错误
  7. shell用户配置详解及bash命令参数
  8. linux 下命令行传参数问题
  9. Linux无法连接网络解决方案

随机推荐

  1. Android 开源优秀项目
  2. Android studio 运行出现Error running a
  3. android Standard Broadcast Actions 的
  4. RecyclerView item imageview 图片宽高自
  5. Android版本信息汇总
  6. Android进度条控件ProgressBar使用
  7. 【转】[译]ANDROID Porting系列
  8. Android(安卓)笔记
  9. Android NDK--(调用c c++ 库)
  10. 实例教程五:采用SharedPreferences保存用