标签: argparse

如何在argparse中添加子分析符的可选位置参数?

我正在尝试使用argparse模块向多个subparser添加所需的输入文件名和可选的输出文件名.

这是我的尝试:

# test_argparse.py

import argparse

def setup_parser():

    parser = argparse.ArgumentParser(prog='test_argparse.py',
                            formatter_class=argparse.RawDescriptionHelpFormatter,
                            description='Testing the argparse module.')

    parser.add_argument('--version', action='version', version='%(prog)s 1.0')

    subparsers = parser.add_subparsers()
    parser_actionA = subparsers.add_parser('actionA')
    parser_actionB = subparsers.add_parser('actionB')
    parser_actionC = subparsers.add_parser('actionC')

    parser.add_argument('infile', nargs=1, help='input mesh file name')
    parser.add_argument('outfile', nargs='?', help='output mesh file name')

    return parser

if __name__ == '__main__':
    parser = setup_parser()
    args = parser.parse_args()
    print args
Run Code Online (Sandbox Code Playgroud)

如果我执行这个:

python test_argparse.py actionA infile outfile
Run Code Online (Sandbox Code Playgroud)

它不起作用,我得到的是:

usage: test_argparse.py [-h] [--version]
                    {actionA,actionB,actionC} ... infile [outfile]
test_argparse.py: error: unrecognized arguments: infile
Run Code Online (Sandbox Code Playgroud)

python python-2.7 argparse

4
推荐指数
1
解决办法
3672
查看次数

Python ArgumentParser嵌套参数

我想用以下签名创建参数解析器:

./myapp [-a [-b BVAL] | -c]

换句话说,用户-b BVAL只有在提供参数的情况下才能提供参数-a.

这是很容易地创建互斥组-a和-c,但我无法弄清楚如何建立关系allow -b only if -a provided

python argparse

4
推荐指数
1
解决办法
2236
查看次数

使用argparse导入脚本的python

A =一个脚本,其结构由命令行调用,其中包含由python argparse库内部解析的选项.B =另一个应该调用A内部函数的脚本.

我相信在B中导入A是我需要的东西,但它返回了我的使用选项,然后退出python解释器.

有没有办法保存A并将其导入B传递给args?或者我应该重写避免解析器使用?

python import argparse

4
推荐指数
1
解决办法
2097
查看次数

单个短划线用于argparse长选项

是否有可能使其--longoption表示为-longoption使用argparse?

argparse.prefix_chars 不起作用,因为假设前缀char将重复一个长选项.

我想也许有一种方法可以关闭短选项并允许长选项使用单个破折号而不是双破折号.像这样的东西:

parser = argparse.ArgumentParser()
parser.turn_off_short_opts()
Run Code Online (Sandbox Code Playgroud)

可以这样做吗?如果没有,我可以用什么来完成这个?

python command-line-interface command-line-arguments argparse

4
推荐指数
1
解决办法
3064
查看次数

对argparse subparser参数进行分组

我有一个包含多个命令的脚本,每个命令都使用add_subparser来获取它自己的必需和/或可选参数集.

=->test.py -h
usage: test.py [-h] <command> ...

positional arguments:
  <command>   Available Commands
    cmd1      Command 1
    cmd2      Command 2
    cmd3      Command 3
    cmd4      Command 4

optional arguments:
  -h, --help  show this help message and exit


=->test.py cmd1 -h
usage: test.py cmd1 [-h] --flag1 FLAG1

optional arguments:
  -h, --help     show this help message and exit
  --flag1 FLAG1  Test flag


=->test.py cmd2 -h
usage: test.py cmd2 [-h] [--flag2 FLAG2]

optional arguments:
  -h, --help     show this help message and exit
  --flag2 FLAG2  Test …
Run Code Online (Sandbox Code Playgroud)

python argparse

4
推荐指数
1
解决办法
2375
查看次数

如何从命名空间中删除参数

问题:给定一个添加了一些参数的argparse解析器实例,有没有办法删除/删除为它定义的参数?

原因:考虑以下例子:

>>>import argparse
>>>parser = argparse.ArgumentParser()
>>>parser.add_argument('--imagePath', action = "store", default = 'toto')
_StoreAction(option_strings=['--imagePath'], dest='imagePath', nargs=None, const=None, default='toto', type=None, choices=None, help=None, metavar=None)
>>>args = parser.parse_args()
>>>args
Namespace(imagePath='toto')
>>>parser.add_argument('--resultPath', action = "store", default = 'titi')
_StoreAction(option_strings=['--resultPath'], dest='resultPath', nargs=None, const=None, default='titi', type=None, choices=None, help=None, metavar=None)
>>>args = parser.parse_args()
>>>args
Namespace(imagePath='toto', resultPath='titi')
Run Code Online (Sandbox Code Playgroud)

如果我们稍后会在脚本中更改args.imagePath的值?

我没有找到更改值的方法,但如果我可以删除/删除参数imagePath,则可以使用新值再次定义imagePath!

python arguments argparse

4
推荐指数
1
解决办法
2807
查看次数

在argparse中使用numpy数据类型

我正在设置一个Argparse解析器来通过shell读取一些用户输入.输入将用于从包含字符串和数字的pandas DataFrame中提取数据.我想type=在Argparse中自动设置参数.add_argument()以匹配相应列的数据类型.

我的想法是设置像这样的Argparse参数,其中inputdata是DataFrame:

for c in inputdata.columns:
        inputname= c
        inputtype= np.dtype(inputdata[c])
        parser.add_argument("--"+inputname, type=inputtype)
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用:Python提出了一个ValueError: dtype('int64') is not callable.我想这是因为我没有给它Numpy文件类型喂它; 如果我将inputtype设置为float,则全部按计划进行.如果我手动输入type=np.int64,Argparse也没有问题.

  • 我怎样才能让它接受我的DataFrame中的文件类型,即上面显示的循环中的int64和object?我在这里尝试了一些选项,例如dtype.type但没有任何效果.

  • 或者这是不可能的?Argparse 文档仅说明了这一点

常见的内置类型和函数可以直接用作类型参数的值

但正如我上面所说,如果明确放入,numpy数据类型似乎很好.

谢谢你的帮助!

python user-input numpy argparse pandas

4
推荐指数
1
解决办法
453
查看次数

使用unittest测试argparse-退出错误

要去关格雷格·哈斯在这个问题的答案,我试图让一个单元测试来检查当我通过它的一些ARGS不存在在该argparse是给相应的错误choices。但是,unittest使用以下try/except语句会产生误报。

另外,当我仅使用一条with assertRaises语句进行测试时,会argparse强制系统退出,并且程序不再执行任何其他测试。

我希望能够对此进行测试,但是鉴于argparse错误退出,也许这是多余的?

#!/usr/bin/env python3

import argparse
import unittest

class sweep_test_case(unittest.TestCase):
    """Tests that the merParse class works correctly"""

    def setUp(self):
        self.parser=argparse.ArgumentParser()
        self.parser.add_argument(
            "-c", "--color",
            type=str,
            choices=["yellow", "blue"],
            required=True)

    def test_required_unknown_TE(self):
        """Try to perform sweep on something that isn't an option.
        Should return an attribute error if it fails.
        This test incorrectly shows that the test passed, even though that must
        not be true."""
        args = …
Run Code Online (Sandbox Code Playgroud)

python unit-testing argparse python-3.x python-unittest

4
推荐指数
2
解决办法
2956
查看次数

如何测试依赖argparse的Python类?

以下粘贴包含来自三个单独的Python文件的相关片段。第一个是从命令行调用的脚本,该脚本在给定某些参数的情况下实例化CIPuller。发生的情况是脚本被调用,类似于:( script.py ci其他argpar被argparse吞噬)。

第二个是名为的子类的一部分Puller。三是子类的部分Puller叫CIPuller。

当调用正确的子类时,这将非常有用,并且使用错误其他args的任何用户都可以查看给定子类的正确args,以及超类的通用参数。(尽管使我脱机了,也许我应该为此使用argparse子命令。)

我被困试图为这些类编写测试。当前,我需要ArgumentParser实例化这些类,但是在测试中,我不是从命令行实例化事物,因此我ArgumentParser没有用。

我尝试ArgumentParser在测试工具中创建一个,以传递给CIPuller's测试代码中的构造函数,但是如果add_argument在那儿使用argparse,则可以理解,当它add_argument在CIPuller构造函数中调用时,会抱怨双(重复)参数。

有什么合适的设计来用参数测试这些类?

#!/usr/bin/env python                                                             

from ci_puller import CIPuller                                                    
import argparse                                                                   
import sys                                                                        

# Using sys.argv[1] for the argument here, as we don't want to pass that onto     
# the subclasses, which should receive a vanilla ArgumentParser                   
puller_type = sys.argv.pop(1)                                                     

parser = argparse.ArgumentParser(                                                 
    description='Throw data into Elasticsearch.'                                  
)                                                                                 

if puller_type == 'ci': …
Run Code Online (Sandbox Code Playgroud)

python pytest argparse

4
推荐指数
1
解决办法
2110
查看次数

使用Python的argparse可选的位置参数

试图解析可选的位置参数我遇到了以下问题:

例:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('infile')
parser.add_argument('outfile', nargs='?')
parser.add_argument('-v', action='store_true')

print(parser.parse_args())
Run Code Online (Sandbox Code Playgroud)

输出:

$ ./x.py -v in out
Namespace(infile='in', outfile='out', v=True)

$ ./x.py in out -v
Namespace(infile='in', outfile='out', v=True)

$ ./x.py in -v out
usage: x.py [-h] [-v] infile [outfile]
x.py: error: unrecognized arguments: out
Run Code Online (Sandbox Code Playgroud)

为什么不接受第三个程序调用?这是argparse的限制吗?

python argparse

4
推荐指数
1
解决办法
1192
查看次数