【问题标题】:python - Using argparse, pass an arbitrary string as an argument to be used in the scriptpython - 使用 argparse,将任意字符串作为要在脚本中使用的参数传递
【发布时间】:2013-06-14 02:15:34
【问题描述】:

如何使用 argparse 将任意字符串定义为可选参数?

示例:

[user@host]$ ./script.py FOOBAR -a -b
Running "script.py"...
You set the option "-a"
You set the option "-b"
You passed the string "FOOBAR"

理想情况下,我希望参数的位置无关紧要。即:

./script.py -a FOOBAR -b == ./script.py -a -b FOOBAR == ./script.py FOOBAR -a -b


在 BASH 中,我可以在使用 getopts 时完成此操作。在 case 循环中处理完所有需要的开关后,我会有一行读取 shift $((OPTIND-1)),然后我可以使用标准 $1$2$3 等访问所有剩余的参数...
argparse 是否存在类似的东西?

【问题讨论】:

  • 你看过 argparse 教程吗?你所描述的一切都在那里
  • iirc 唯一未讨论的部分是 nargs="*" 行为(因此一个位置参数可以获取所有剩余参数)
  • @Nirk,棘手的是如果你只使用parse_args,一旦它看到一个“位置”参数,它就会停止寻找其他参数并从位置参数中收集参数到最后。在大多数情况下这很好,但会破坏他的第一个和第三个例子。
  • @Nirk 另外,这个传递的字符串应该是可选的。如果我做一个香草add_argument("word"),它就变成了强制性的。
  • 看起来 argparse 本身并不能处理 optional 任意参数。使用@jedwards 答案,我可以获得所需的功能,除了 argparse 不知道任意字符串,因此调用help 对话框的用户不知道使用任意字符串的能力。

标签: python python-2.7 python-3.x


【解决方案1】:

要准确获得所需内容,诀窍是使用parse_known_args() 而不是parse_args()

#!/bin/env python 

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")

opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder (opts[1] is a list (possibly empty) of all remaining args)
if opts[1]: print('You passed the strings %s' % opts[1])

编辑:

以上代码显示如下帮助信息:

./clargs.py -h 用法:clargs_old.py [-h] [-a] [-b] 可选参数: -h, --help 显示此帮助信息并退出 -一种 -b

如果你想告知用户可选的任意参数,我能想到的唯一解决方案是继承 ArgumentParser 并自己编写。

例如:

#!/bin/env python 

import os
import argparse

class MyParser(argparse.ArgumentParser):
    def format_help(self):
        help = super(MyParser, self).format_help()
        helplines = help.splitlines()
        helplines[0] += ' [FOO]'
        helplines.append('  FOO         some description of FOO')
        helplines.append('')    # Just a trick to force a linesep at the end
        return os.linesep.join(helplines)

parser = MyParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")

opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder
if opts[1]: print('You passed the strings %s' % opts[1])

其中显示以下帮助信息:

./clargs.py -h 用法:clargs.py [-h] [-a] [-b] [FOO] 可选参数: -h, --help 显示此帮助信息并退出 -一种 -b FOO 对 FOO 的一些描述

注意在“用法”行中添加了[FOO],在“可选参数”下的帮助中添加了FOO

【讨论】:

  • 这很好,只是我丢失了 argparse 中用于可选字符串的内置帮助对话框。
  • 这是真的。我能想到的唯一解决方案是将 ArgumentParser 子类化并自己编写。请注意,您必须跳过此循环的唯一原因是因为您希望参数的任何顺序都有效。我将使用子类化 ArgumentParser 的示例来编辑我的答案。
  • 哇,谢谢! argparse 中没有一个选项可以让可选参数成为任意字符串,这似乎很奇怪......哦,好吧。非常感谢您的回答。
猜你喜欢
  • 2018-11-19
  • 1970-01-01
  • 2017-03-12
  • 2018-06-25
  • 2021-02-28
  • 2017-10-04
  • 2022-12-09
  • 2016-09-15
  • 2012-06-03
相关资源
最近更新 更多