标签: argparse

从 Python 中的命名空间对象导入变量

假设我有一个args通过调用获得的命名空间parser.parse_args(),它解析命令行参数。

如何将此命名空间中的所有变量导入到当前命名空间?

例如

parser.add_argument('-p', '--some_parameter', default=1)

args = parser.parse_args()

# ... code to load all variables defined in the namespace args ...

print some_parameter
Run Code Online (Sandbox Code Playgroud)

我当然可以这样做:

some_parameter = args.some_parameter
Run Code Online (Sandbox Code Playgroud)

但如果我有大量参数,则每个参数都需要这样一行。

是否有另一种方法可以从命名空间导入变量,而不必逐一遍历它们?

PSfrom args import *不起作用。

PS2:我知道这是一个不好的做法,但这在某些极端情况下会有所帮助,例如我们在快速构建代码原型和测试

python namespaces argparse

2
推荐指数
1
解决办法
2523
查看次数

使用 run -m 时将参数传递给 IPython 中的模块

我刚刚安装了 IPython 的 git master 分支。下列:

In [1]: run -m my_packages.my_module -verbosity 20
Run Code Online (Sandbox Code Playgroud)

返回错误:

UsageError: option -v not recognized ( allowed: "nidtN:b:pD:l:rs:T:em:G" )
Run Code Online (Sandbox Code Playgroud)

尽管以下方法有效:

$ python -m my_packages.my_module -verbosity 20
Run Code Online (Sandbox Code Playgroud)

我使用argparse如下:

parser = argparse.ArgumentParser(description='my_program')
parser.add_argument('-verbosity',   help='Verbosity', required=True)
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

python ipython argparse

2
推荐指数
1
解决办法
2016
查看次数

argparse 具有不同的模式

我在使用 argparse 时遇到一些困难。我有一个 GUI 应用程序,我想像这样使用:

  1. GUI.exe => 打开 GUI 应用程序
  2. GUI.exe -s file_directory1 => 无需打开即可播放 GUIX.exe
  3. GUI.exe -s file_directory1 -o file_directory2 => 与 2 相同。

不允许这样做:GUI.exe -o file_directory

我知道如何做 1 和 2,但不知道如何做 3

有人已经这样做过或者可以给我一些线索吗?

预先感谢您的帮助。

python argparse

2
推荐指数
1
解决办法
3968
查看次数

argparse 可以接受参数值作为 key=val 对

我正在尝试使用 argparse 来实现以下选项(由于项目要求,不能使用 docopt 等任何其他工具):-

cli.py --conf key1=value1, key2=value2, kay3=value3
or
cli.py --conf key1=value1 key2=value2 key3=value3
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试过type=json.loads或听从但没有帮助。一种可能的解决方案是使用type=str然后将其解析为dict. 你们知道我缺少的其他更好的解决方案吗?提前致谢。

注意-不能使用 --key1=value1 --key2=value2 --key3=value3 因为我不想限制键/值的计数和名称。它将有助于将来支持新的键/值。

python python-2.7 argparse

2
推荐指数
1
解决办法
3359
查看次数

如何减少argparse中参数帮助的缩进级别?

我正在使用 Python 的argparse,我希望参数帮助文本的缩进更少。这argparse是生成的内容:

$ ./help.py -h
usage: help.py [-h] [--program-argument PROGRAM_ARGUMENT]

Description of program

optional arguments:
  -h, --help            show this help message and exit
  --program-argument PROGRAM_ARGUMENT
                        This is some help text about --program-argument. For example:

                            --program-argment "You can supply a string as the program argument"
Run Code Online (Sandbox Code Playgroud)

我希望它产生更像这样的东西:

$ ./help.py -h
usage: help.py [-h] [--program-argument PROGRAM_ARGUMENT]

Description of program

optional arguments:
  -h, --help            show this help message and exit
  --program-argument PROGRAM_ARGUMENT
      This is some help text about --program-argument. …
Run Code Online (Sandbox Code Playgroud)

python argparse

2
推荐指数
1
解决办法
799
查看次数

python 3 argparse调用一个函数

我想在python3中创建一个类似命令行/类似shell的界面。

Argparse 似乎负责解析和显示帮助/错误消息。根据argparsepython3 文档,有一个func=参数可用于让您的函数被 argparse 调用

# sub-command functions
def foo(args):
   print(args.x * args.y)
def bar(args):
    print('((%s))' % args.z)
# create the top-level parser
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
# create the parser for the "foo" command
parser_foo = subparsers.add_parser('foo')
parser_foo.add_argument('-x', type=int, default=1)
parser_foo.add_argument('y', type=float)
parser_foo.set_defaults(func=foo)
# create the parser for the "bar" command
parser_bar = subparsers.add_parser('bar')
parser_bar.add_argument('z')
parser_bar.set_defaults(func=bar)
Run Code Online (Sandbox Code Playgroud)

但据我所知help_parser.set_defaults(func=foo),不会调用我的函数。如果你能帮助我,我将不胜感激。

您可以通过使用 python3 运行程序,键入help然后按 [Enter]来重现该问题。它没有hello按预期打印。谢谢!

def …
Run Code Online (Sandbox Code Playgroud)

parsing function command-line-interface argparse python-3.x

2
推荐指数
1
解决办法
1371
查看次数

如何在Python中通过命名空间对象访问argparse位置参数

我试图通过 argparse 使用位置参数,但我无法访问这个参数值...我尝试查看 python 中关于 argparse 的文档,但我没有找到任何真正清晰的内容,也没有在不同的线程上找到任何内容。 。

这是我的代码:

parser = argparse.ArgumentParser(description='valid arguments')
parser.add_argument('file_liste', type=str, help='give a valid list')
args = parser.parse_args()
print(args)
Run Code Online (Sandbox Code Playgroud)

这是我得到的结果:

Namespace(file_liste='my_list.txt')
Run Code Online (Sandbox Code Playgroud)

这是我启动脚本的命令行:

python my_script.py my_list.txt
Run Code Online (Sandbox Code Playgroud)

我想要的是我的脚本采用 txt 文件作为参数来读取它,但我无法访问应存储在名为“file_liste”的变量中的值。

我尝试了这个,但出现错误:

print(args[0], "this is args[0]")
TypeError: 'Namespace' object does not support indexing
Run Code Online (Sandbox Code Playgroud)

这可能是一件愚蠢的事情,但我没有找到任何我能理解的答案......

python argparse

2
推荐指数
1
解决办法
2986
查看次数

Python argparse 通过命令行传递列表或字典

我已经看到有关使用 argparse 库将字典和列表传递给 Python 的问题。这些示例都显示了我的 Python 代码的样子。但是没有人告诉我它们在命令行上的样子。我在哪里需要大括号、方括号和引号?

因此,如果我想要参数 --my_dict 和 --my_list 我将如何将它们指定为从命令行调用?

这是我想要完成的事情的本质:

Python foo.py --my_dict="{'Name': 'Zara', 'Class': 'First'}" --my_list="['a', 'b', 'c']"
Run Code Online (Sandbox Code Playgroud)

python argparse

2
推荐指数
1
解决办法
2700
查看次数

argparse:如何允许单个参数有多个名称?

是否可以使用多个名称来引用 argparse 中的单个参数?具体来说,我想允许用户通过下划线和连字符(破折号)指定参数?

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input-file')
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

例如,我希望以下两个选项都适用于参数args.input_file

python main.py --input-file /tmp/file
python main.py --input_file /tmp/file
Run Code Online (Sandbox Code Playgroud)

python argparse

2
推荐指数
1
解决办法
857
查看次数

如何通过传递命令行参数测试 __name__ == "__main__" 是否?

嗨,我想测试我的可执行模块main.py。在这个模块中有main()一个接受两个参数的函数:

# main.py

def main(population_size: int, number_of_iterations: int):
    ...
Run Code Online (Sandbox Code Playgroud)

在这个模块的底部有一个接受命令行参数并执行main函数的逻辑:

# main.py

if __name__ == "__main__":
    # create parser and handle arguments
    PARSER = argparse.ArgumentParser()
    PARSER.add_argument("--populationSize",
                        type=int,
                        default=-1,
                        help="Number of individuals in one iteration")
    PARSER.add_argument("--numberOfIterations",
                        type=int,
                        default=-1,
                        help="Number of iterations in one run")
    # parse the arguments
    ARGS = PARSER.parse_args()

    main(ARGS.populationSize, ARGS.numberOfIterations)
Run Code Online (Sandbox Code Playgroud)

我想测试传递的命令行参数。我的测试方法不起作用:

# test_main.py

@staticmethod
@mock.patch("argparse.ArgumentParser.parse_args")
@mock.patch("main.main")
def test_passing_arguments(mock_main, mock_argparse):
    """Test passing arguments."""
    mock_argparse.return_value = argparse.Namespace(
         populationSize=4, numberOfIterations=3)
    imp.load_source("__main__", "main.py")

    mock_main.assert_called_with(4, 3)
Run Code Online (Sandbox Code Playgroud)

我得到的错误 …

python unit-testing mocking argparse

2
推荐指数
1
解决办法
1286
查看次数