argparse

Passing integer lists to python

本秂侑毒 提交于 2019-11-30 22:56:46
问题 I want to pass 2 lists of integers as input to a python program. For e.g, (from command line) python test.py --a 1 2 3 4 5 -b 1 2 The integers in this list can range from 1-50, List 2 is subset of List1. Any help/suggestions ? Is argparse the right module ? Any concerns in using that ? I have tried : import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--a', help='Enter list 1 ') parser.add_argument('--b', help='Enter list 2 ') args = parser.parse

How to use python argparse with args other than sys.argv?

大兔子大兔子 提交于 2019-11-30 22:07:01
问题 I've been all over the documentation and it seems like there's no way to do it, but: Is there a way to use argparse with any list of strings, instead of only with sys.argv? Here's my problem: I have a program which looks something like this: # This file is program1.py import argparse def main(argv): parser = argparse.ArgumentParser() # Do some argument parsing if __name__ == '__main__': main(sys.argv) This works fine when this program is called straight from the command line. However, I have

Python: argparse subcommand subcommand?

倖福魔咒の 提交于 2019-11-30 20:29:26
I have a program that has many available options. For example a configuration option to change settings. ./app config -h gives me the help using normal argparse subcommands now i would like to add another subcommand to the config subcommand called list to list config values ./app config list additionally that command should accept another option so that i could say ./app config list CATEGORY only to list the config of one category my code right now is basically this just with more commands >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers(title='subcommands', ...

Python Read from Stdin with Arguments

喜夏-厌秋 提交于 2019-11-30 19:52:38
问题 I want to read from python stdin but also to have input options in my program. When I try to pass an option to my programm I get the error file not found and my arguments are discarded. For parsing the arguments I use the following code: parser=argparse.ArgumentParser(description='Training and Testing Framework') parser.add_argument('--text', dest='text', help='The text model',required=True) parser.add_argument('--features', dest='features', help='The features model',required=True) parser.add

python unittest for argparse

拈花ヽ惹草 提交于 2019-11-30 19:31:42
问题 I have a function inside a module that creates an argparse : def get_options(prog_version='1.0', prog_usage='', misc_opts=None): options = [] if misc_opts is None else misc_opts parser = ArgumentParser(usage=prog_usage) if prog_usage else ArgumentParser() parser.add_argument('-v', '--version', action='version', version='%(prog)s {}'.format(prog_version)) parser.add_argument('-c', '--config', dest='config', required=True, help='the path to the configuration file') for option in options: if

python argparse例子实践

ぐ巨炮叔叔 提交于 2019-11-30 19:28:39
python 解析命令行读取参数,在多个文件或者不同语言协同的项目中,python脚本经常需要从命令行直接读取参数。 万能的python自带了sys.arg、argparse、optparse模块等,使读取命令行参数变得简单而规范。 sys.argv 解释:就是一个从程序外部获取参数的桥梁,因为我们从外部取得的参数可以是多个,所以获得的是一个列表(list),也就是说sys.argv可以看作是一个列表,所以才用[]提取其中的元素。 第一个元素是程序本身,后续的才依次是外部给与的参数。 1. sys.argv 是命令行参数列表 2. len(sys.argv)是命令行参数个数 3. sys.argv[0]表示脚本名 4. 注意参数顺序 实例 import sys print(sys.argv) #['test_argv.py', 'hello', 'python'] print(len(sys.argv)) #3 print('第一个参数',sys.argv[0]) test_argv.py 执行命令: python 脚本名称 params params1 argparse模块 1) 一般模式 大多数情况下,脚本很可能需要多个参数,而且每次参数的类型用处各不相同,那么这个时候在参数钱添加标签表明参数的类型和用途十分有用,而利用argparse模块可以方便的实现这一目的。举例如下:

Python argparse: type inconsistencies when combining 'choices', 'nargs' and 'default'

﹥>﹥吖頭↗ 提交于 2019-11-30 19:07:43
I have the following python program: #!/usr/bin/env python import argparse parser = argparse.ArgumentParser() parser.add_argument('arg', choices=['foo', 'bar', 'baz'], default='foo', nargs='*') args = parser.parse_args() print(args) If I invoke the program like this: ./prog.py the output is Namespace(arg='foo') But if I invoke the program with foo as an argument: ./prog.py foo the output is Namespace(arg=['foo']) Question How can I get arg 's default value to become a list ? I've tried I've tried setting default=['foo'] but that results in: prog.py: error: argument arg: invalid choice: ['foo']

Python argparse: command-line argument that can be either named or positional

限于喜欢 提交于 2019-11-30 18:50:01
I am trying to make a Python program that uses the argparse module to parse command-line options. I want to make an optional argument that can either be named or positional. For example, I want myScript --username=batman to do the same thing as myScript batman . I also want myScript without a username to be valid. Is this possible? If so, how can it be done? I tried various things similar to the code below without any success. parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("-u", "--user-name", default="admin") group.add_argument("user-name",

Catching ArgumentTypeError exception from custom action

百般思念 提交于 2019-11-30 18:44:54
What is the best practice to throw an ArgumentTypeError exception from my own custom action and let the argparse to catch it for me? It seems that argparse's try/except block does not handle this exception for my custom actions. Though it does that just fine for its built-in actions. class unique_server_endpoints(argparse.Action): """This class avoids having two duplicate OuterIPs in the client argument list""" def __call__(self, parser, namespace, values, option_string=None): ips = set() endpoints = [] for r in values: ep = server_endpoint(r) if ep[0] in ips: raise argparse.ArgumentTypeError(

Python argparse positional arguments and sub-commands

拈花ヽ惹草 提交于 2019-11-30 18:16:31
I'm working with argparse and am trying to mix sub-commands and positional arguments, and the following issue came up. This code runs fine: import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() parser.add_argument('positional') subparsers.add_parser('subpositional') parser.parse_args('subpositional positional'.split()) The above code parses the args into Namespace(positional='positional') , however when I change the positional argument to have nargs='?' as such: import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() parser.add