标签: argparse

Python和argparse的多个位置参数

我正在尝试使用argparse来解析我正在处理的程序的命令行参数.本质上,我需要支持在可选参数中传播的多个位置参数,但是在这种情况下无法使argparse工作.在实际程序中,我正在使用自定义操作(我需要在每次找到位置参数时存储命名空间的快照),但我可以使用操作复制我遇到的问题append:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-a', action='store_true')
>>> parser.add_argument('-b', action='store_true')
>>> parser.add_argument('input', action='append')
>>> parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
usage: ipython [-h] [-a] [-b] input
ipython: error: unrecognized arguments: filetwo filethree
Run Code Online (Sandbox Code Playgroud)

我希望这会导致命名空间(a=True, b=True, input=['fileone', 'filetwo', 'filethree']),但无法看到如何做到这一点 - 如果它确实可以.如果有可能的话,我在文档或谷歌中看不到任何一种说法,尽管它很可能(很可能?)我忽略了一些东西.有没有人有什么建议?

python argparse

24
推荐指数
3
解决办法
3万
查看次数

argparse.add_argument()中的type = dict

我正在尝试将字典设置为可选参数(使用argparse); 以下是我到目前为止的内容:

parser.add_argument('-i','--image', type=dict, help='Generate an image map from the input file (syntax: {\'name\': <name>, \'voids\': \'#08080808\', \'0\': \'#00ff00ff\', \'100%%\': \'#ff00ff00\'}).')
Run Code Online (Sandbox Code Playgroud)

但是运行脚本:

 $ ./script.py -i {'name': 'img.png','voids': '#00ff00ff','0': '#ff00ff00','100%': '#f80654ff'}

script.py: error: argument -i/--image: invalid dict value: '{name:'
Run Code Online (Sandbox Code Playgroud)

即使在翻译中,

>>> a={'name': 'img.png','voids': '#00ff00ff','0': '#ff00ff00','100%': '#f80654ff'}
Run Code Online (Sandbox Code Playgroud)

工作得很好.

那么我应该如何传递参数呢?提前致谢.

python dictionary argparse

24
推荐指数
5
解决办法
2万
查看次数

命名空间,argparse和用法

这真的是几个问题:

  1. 有没有理由argparse使用命名空间而不是字典?

  2. 假设我有一堂课__init__(self, init_method, *args).该init_method参数告诉init_function我想要初始化类的方式,而arg参数给出了init所需的所有参数.对于不同的方法,参数可能不同.我应该使用字典还是命名空间?

  3. 假设我使用命名空间,如何将命名空间传递给__init__()

python namespaces argparse

23
推荐指数
2
解决办法
9977
查看次数

将"help"移动到python argparse中的另一个Argument Group

目前我正在使用Python创建目录读取器程序.我正在使用'argparse'来解析命令行中的参数.我有以下代码:

parser = argparse.ArgumentParser(prog = "LS.py",
                                 usage = "%(prog)s [options] [path1 [path2 [...pathN]]]\nThe paths are optional; if not given . is used.")

group = parser.add_argument_group("Options")

group.add_argument("-path", default = ".", help = argparse.SUPPRESS, metavar = "")
group.add_argument("-m", "--modified", default = False,
                    help = "show last modified date/time [default: off]",
                    metavar = "")
group.add_argument("-o ORDER", "--order=ORDER", nargs = 2, default = "name",
                    help = "order by ('name', 'n', 'modified', 'm', 'size', 's')\n[default: name]",
                    metavar = "")
group.add_argument("-r", "--recursive", default = False,
                    help …
Run Code Online (Sandbox Code Playgroud)

python argparse

23
推荐指数
2
解决办法
6818
查看次数

Python argparse required = True但是--version功能?

在我所有的脚本,我用的是标准的标志--help--version,但我似乎无法弄清楚如何使--versionparser.add_argument(..., required=True).

import sys, os, argparse

parser = argparse.ArgumentParser(description='How to get --version to work?')

parser.add_argument('--version', action='store_true', 
                    help='print version information')
parser.add_argument('-H', '--hostname', dest='hostname', required=True, 
                    help='Host name, IP Address')
parser.add_argument('-d', '--database', dest='database', required=True,
                    help='Check database with indicated name')
parser.add_argument('-u', '--username', dest='username', required=True, 
                    help='connect using the indicated username')
parser.add_argument('-p', '--password', dest='password', required=True, 
                    help='use the password to authenticate the connection')

args = parser.parse_args()

if args.version == True:
    print 'Version information here'

$ ./arg.py  --version 
usage: arg.py …
Run Code Online (Sandbox Code Playgroud)

python command-line-arguments argparse

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

如何使用Python Argparse制作所需参数的短版和长版?

我想指定一个被调用的必需参数,inputdir但我也希望有一个名为的简写版本i.我没有看到一个简洁的解决方案来做这个,没有做任何可选的参数,然后做我自己的检查.有没有一个首选的做法,我没有看到或唯一的方法是使两个可选和我自己的错误处理?

这是我的代码:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inputdir", help="Specify the input directory")
parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

python command-line-arguments argparse

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

TypeError:__ init __()在argparse中得到了一个意外的关键字参数'type'

嘿所以我正在使用argparse尝试生成季度报告.这就是代码的样子:

parser  = argparse.ArgumentParser()

parser.add_argument('-q', "--quarter",  action='store_true', type=int, help="Enter a Quarter number: 1,2,3, or 4 ")
parser.add_argument('-y', "--year", action='store_true',type=str,help="Enter a year in the format YYYY ")
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

TypeError:init()得到一个意外的关键字参数'type'

据我所知,argparse文档类型是add_argument函数的一个参数.我尝试删除此并将代码更新为:

parser  = argparse.ArgumentParser()

parser.add_argument('-q', "--quarter",  action='store_true', help="Enter a Quarter number: 1,2,3, or 4 ")
parser.add_argument('-y', "--year", action='store_true',help="Enter a year in the format YYYY ")
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

然后我尝试用它运行它:python scriptname.py -q 1 -y 2015它给了我以下错误:

错误:无法识别的参数:2015年1月

我不知道为什么会这样.任何人都可以对此有所了解.

python parsing argparse

22
推荐指数
2
解决办法
2万
查看次数

为什么 argparse 不接受“--”作为参数?

我的脚本采用-d,--delimiter作为参数:

parser.add_argument('-d', '--delimiter')
Run Code Online (Sandbox Code Playgroud)

但是当我将它--作为分隔符传递时,它是空的

script.py --delimiter='--' 
Run Code Online (Sandbox Code Playgroud)

我知道--参数/参数解析很特殊,但我在表单中使用它--option='--'并引用它。

为什么它不起作用?我正在使用Python 3.7.3

这是测试代码:

#!/bin/python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--delimiter')
parser.add_argument('pattern')

args = parser.parse_args()

print(args.delimiter)
Run Code Online (Sandbox Code Playgroud)

当我运行它时,script --delimiter=-- AAA它打印为空args.delimiter

python argparse

22
推荐指数
2
解决办法
2746
查看次数

argparse模块在Python中不起作用

我正在尝试使用Python工作的argparse模块.我的问题是,在全新安装时,我得到以下内容:

File "test.py", line 3, in <module>
import argparse
File "/home/jon/Pythons/realmine/argparse.py", line 3, in <module>
parser = argparse.ArgumentParser(description='Short sample app')
AttributeError: 'module' object has no attribute 'ArgumentParser'
Run Code Online (Sandbox Code Playgroud)

test.py 是:

import argparse
Run Code Online (Sandbox Code Playgroud)

显然,我错过了一些东西.有人可以帮忙吗?

python argparse

21
推荐指数
1
解决办法
1万
查看次数

argparse参数嵌套

我在python中有以下代码:

parser = argparse.ArgumentParser(description='Deployment tool')
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', '--add', dest='name_to_add', help='Add a new group or a role to existing group')
group.add_argument('-u', '--upgrade', dest='name_to_upgrade', help='Upgrade a group with the new version')
parser.add_argument('--web_port', help='Port of the WEB instance that is being added to the group')
Run Code Online (Sandbox Code Playgroud)

我的问题是"--web_port"选项.我希望能够仅使用"-a"选项添加此选项,但不能使用"-u"添加此选项.

希望能够运行:"python my_script.py -a name --web_port = XXXX".

不想运行:"python my_script.py -u name --web_port = XXXX"

我应该如何更改代码以便能够以这种方式运行它?

谢谢,阿尔沙夫斯基亚历山大.

python argparse

21
推荐指数
1
解决办法
7604
查看次数