argparse

Argparse入门介绍

一世执手 提交于 2020-02-01 10:07:02
argparse 模块是 Python 标准库中推荐的命令行解析模块。 下面链接所示为argparse的官方doc教程 链接: https://docs.python.org/zh-cn/3/howto/argparse.html#id1 文档是python3版本,如果使用python2允许则会出现相应的错误. (linux下直接输入python 默认的是Python2,输入python3才能执行python3) --------------------------------------------------------------- 针对该文档,如果用python2可能出现的问题记录: 1. 原文: 我在用python2时实际执行时的结果: 2. 原文: 我在用python2时实际执行时的结果: 来源: CSDN 作者: 小飞侠985 链接: https://blog.csdn.net/a806689294/article/details/104113649

Python 基础(二十一):argparse 模块

ぃ、小莉子 提交于 2020-01-31 10:40:19
目录 1. 简介 2. 使用 1. 简介 argparse 模块主要用于处理 Python 命令行参数和选项,程序定义好所需参数后,该模块会通过 sys.argv 解析出那些参数;除此之外,argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。使用 argparse 模块,我们可以轻松的编写出用户友好的命令行接口。 2. 使用 我们先来看一个简单示例: import argparse # 创建解析对象 parser = argparse . ArgumentParser ( ) # 解析 parser . parse_args ( ) 文件名为 test.py ,在控制输入命令: python test.py --help ,执行结果: usage : test . py [ - h ] optional arguments : - h , - - help show this help message and exit 通过上面的执行结果,我们可以看出 Python 的可选参数包括: --help 和其简写 -h ,Python 使用 - 来指定短参数,使用 -- 来指定长参数 ,我们执行一下 python test.py -h ,执行结果: usage : test . py [ - h ] optional arguments : - h

python argparse — customizing error messages

北城以北 提交于 2020-01-31 04:59:08
问题 I want to generate custom error messages for particular usage errors in my command-line program that uses the argparse library. I know I can override the general presentation of the error by subclassing argparse.ArgumentParser : class HelpParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) sys.exit(2) parser = HelpParser(... ...) args = parser.parse_args() But when my error method is called, message has already been formatted by the library.

Is it possible to use argparse to capture an arbitrary set of optional arguments?

情到浓时终转凉″ 提交于 2020-01-25 06:54:12
问题 Is it possible to use argparse to capture an arbitrary set of optional arguments? For example both the following should be accepted as inputs: python script.py required_arg1 --var1 value1 --var2 value2 --var3 value3 python script.py required_arg1 --varA valueA --var2 value2 --varB valueB a priori I don't know what optional arguments would be specified receive but would handle them accordingly. 回答1: This is kind of a hackish way, but it works very well: Check, which arguments are not added and

Is it possible to use argparse to capture an arbitrary set of optional arguments?

独自空忆成欢 提交于 2020-01-25 06:54:08
问题 Is it possible to use argparse to capture an arbitrary set of optional arguments? For example both the following should be accepted as inputs: python script.py required_arg1 --var1 value1 --var2 value2 --var3 value3 python script.py required_arg1 --varA valueA --var2 value2 --varB valueB a priori I don't know what optional arguments would be specified receive but would handle them accordingly. 回答1: This is kind of a hackish way, but it works very well: Check, which arguments are not added and

Python argparse check if flag is present while also allowing an argument

大城市里の小女人 提交于 2020-01-24 19:56:46
问题 How do I check if the flag --load is present? #!/usr/bin/env python3 import argparse import os parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-l', '--load', nargs='?', metavar='path', help='Load all JSON files recursively in path') args = parser.parse_args() print(args) Calling the script with --load outputs the following: Namespace(load=None) I can't omit nargs='?' and use action='store_true' as I'd like to allow an argument to be passed, for

Is there any way to get argparse.ArgumentParser.parse_args() not to exit on argument errors?

孤者浪人 提交于 2020-01-23 11:16:49
问题 For example: import argparse parser = arparse.ArgumentParser() # parser.add_argument(...) ... args = parser.parse_args(args_list) The problem is, parser.parse_args automatically exits if there is an error in args_list . Is there a setting that gets it to raise a friendlier exception instead? I do not want to have to catch a SystemExit and extract the needed error message from it if there is any way around it. 回答1: You could use args, unknown = parser.parse_known_args(args_list) Then, any

python学习之argparse模块

人走茶凉 提交于 2020-01-23 05:16:18
argparse 模块可以编写用户友好的命令行界面。 class argparse.ArgumentParser( prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True) 创建一个新的ArgumentParser对象。 所有参数应作为关键字参数传递。 每个参数在下面有其自己的更详细的描述,但简言之,它们是: prog - 程序的名称(默认值:sys.argv [0])usage - 描述程序使用的字符串(默认值:从添加到解析器的参数生成)description - 在参数帮助之前显示的文本(默认值:无)epilog - 参数帮助后显示的文本(默认值:无)parents - 也应包含其参数的ArgumentParser对象的列表formatter_class - 用于自定义帮助输出的类prefix_chars - 可选参数前缀的字符集(默认值:' - ')fromfile

Parameter dependencies in Python - can't make it work

六眼飞鱼酱① 提交于 2020-01-23 02:45:10
问题 I am trying to add a parameter dependency to my script. The idea is that --clone argument will require non-empty --gituser . After perusing this example, I tried the following In [93]: class CloneAction(argparse.Action): ...: def __call__(self, parser, namespace, _): ...: if not namespace.git_user and namespace.clone: ...: parser.error('"--clone" requires legal git user') ...: In [94]: parser = argparse.ArgumentParser() In [95]: parser.add_argument('-g', '--gituser', dest='git_user', type=str

Require either of two arguments using argparse

十年热恋 提交于 2020-01-22 04:09:49
问题 Given: import argparse pa = argparse.ArgumentParser() pa.add_argument('--foo') pa.add_argument('--bar') print pa.parse_args('--foo 1'.split()) how do I make at least one of "foo, bar" mandatory: --foo x , --bar y and --foo x --bar y are fine make at most one of "foo, bar" mandatory: --foo x or --bar y are fine, --foo x --bar y is not 回答1: I think you are searching for something like mutual exclusion (at least for the second part of your question). This way, only foo or bar will be accepted,