在没有任何参数的情况下调用脚本时,使用 python argparse 显示帮助消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4042452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:58:54  来源:igfitidea点击:

Display help message with python argparse when script is called without any arguments

pythonargparse

提问by musashiXXX

This might be a simple one. Assume I have a program that uses argparse to process command line arguments/options. The following will print the 'help' message:

这可能是一个简单的。假设我有一个使用 argparse 处理命令行参数/选项的程序。以下将打印“帮助”消息:

./myprogram -h

or:

或者:

./myprogram --help

But, if I run the script without any arguments whatsoever, it doesn't do anything. What I want it to do is to display the usage message when it is called with no arguments. How is that done?

但是,如果我在没有任何参数的情况下运行脚本,它不会做任何事情。我想要它做的是在不带参数的情况下调用它时显示使用消息。这是怎么做的?

采纳答案by unutbu

This answer comes from Steven Bethard on Google groups. I'm reposting it here to make it easier for people without a Google account to access.

这个答案来自Google 群组的Steven Bethard 。我在这里重新发布它是为了让没有 Google 帐户的人更容易访问。

You can override the default behavior of the errormethod:

您可以覆盖该error方法的默认行为:

import argparse
import sys

class MyParser(argparse.ArgumentParser):
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)

parser = MyParser()
parser.add_argument('foo', nargs='+')
args = parser.parse_args()


Note that the above solution will print the help message whenever the errormethod is triggered. For example, test.py --blahwill print the help message too if --blahisn't a valid option.

请注意,无论何时error触发该方法,上述解决方案都会打印帮助消息。例如,test.py --blah如果--blah不是有效选项,也会打印帮助消息。

If you want to print the help message only if no arguments are supplied on the command line, then perhaps this is still the easiest way:

如果您只想在命令行上没有提供参数时才打印帮助消息,那么这可能仍然是最简单的方法:

import argparse
import sys

parser=argparse.ArgumentParser()
parser.add_argument('foo', nargs='+')
if len(sys.argv)==1:
    parser.print_help(sys.stderr)
    sys.exit(1)
args=parser.parse_args()


Note that parser.print_help()prints to stdout by default. As init_js suggests, use parser.print_help(sys.stderr)to print to stderr.

请注意,parser.print_help()默认情况下会打印到标准输出。正如init_js 建议的那样,用于parser.print_help(sys.stderr)打印到 stderr。

回答by vacri

Instead of writing a class, a try/except can be used instead

可以使用 try/except 代替编写类

try:
    options = parser.parse_args()
except:
    parser.print_help()
    sys.exit(0)

The upside is that the workflow is clearer and you don't need a stub class. The downside is that the first 'usage' line is printed twice.

好处是工作流程更清晰,您不需要存根类。缺点是第一个“用法”行打印了两次。

This will need at least one mandatory argument. With no mandatory arguments, providing zero args on the commandline is valid.

这至少需要一个强制参数。没有强制参数,在命令行上提供零参数是有效的。

回答by cgseller

With argparse you could do:

使用 argparse 你可以这样做:

parser.argparse.ArgumentParser()
#parser.add_args here

#sys.argv includes a list of elements starting with the program
if len(sys.argv) < 2:
    parser.print_usage()
    sys.exit(1)

回答by pauricthelodger

Throwing my version into the pile here:

把我的版本扔到这里:

import argparse

parser = argparse.ArgumentParser()
args = parser.parse_args()
if not vars(args):
    parser.print_help()
    parser.exit(1)

You may notice the parser.exit- I mainly do it like that because it saves an import line if that was the only reason for sysin the file...

您可能会注意到parser.exit- 我主要是这样做的,因为如果这是sys文件中的唯一原因,它会保存导入行...

回答by pd321

If you have arguments that must be specified for the script to run - use the requiredparameter for ArgumentParser as shown below:-

如果您必须为脚本指定参数才能运行 - 使用ArgumentParser所需的参数,如下所示:-

parser.add_argument('--foo', required=True)

parse_args() will report an error if the script is run without any arguments.

如果脚本在没有任何参数的情况下运行,parse_args() 将报告错误。

回答by AManOfScience

If you associate default functions for (sub)parsers, as is mentioned under add_subparsers, you can simply add it as the default action:

如果您为(子)解析器关联默认函数,如下所述add_subparsers,您可以简单地将其添加为默认操作:

parser = argparse.ArgumentParser()
parser.set_defaults(func=lambda x: parser.print_usage())
args = parser.parse_args()
args.func(args)

Add the try-except if you raise exceptions due to missing positional arguments.

如果由于缺少位置参数而引发异常,请添加 try-except。

回答by zerocog

Set your positional arguments with nargs, and check if positional args are empty.

使用 nargs 设置位置参数,并检查位置参数是否为空。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
    parser.print_help()

Reference Python nargs

参考Python nargs

回答by Ievgen Popovych

The cleanest solution will be to manually pass default argument if none were given on the command line:

如果命令行上没有给出默认参数,最干净的解决方案是手动传递默认参数:

parser.parse_args(args=None if sys.argv[1:] else ['--help'])

Complete example:

完整示例:

import argparse, sys

parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost', help='Host to connect to')
# parse arguments
args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])

# use your args
print("connecting to {}".format(args.host))

This will print complete help (not short usage) if called w/o arguments.

如果调用没有参数,这将打印完整的帮助(不是简短的用法)。

回答by ThorSummoner

parser.print_help()
parser.exit()


The parser.exitmethod also accept a status(returncode), and a messagevalue (include a trailing newline yourself!).

parser.exit方法还接受一个status(返回码)和一个message值(包括您自己的尾随换行符!)。

an opinionated example, :)

一个固执的例子,:)

#!/usr/bin/env python3

""" Example argparser based python file
"""

import argparse

ARGP = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawTextHelpFormatter,
)
ARGP.add_argument('--example', action='store_true', help='Example Argument')


def main(argp=None):
    if argp is None:
        argp = ARGP.parse_args()  # pragma: no cover

    if 'soemthing_went_wrong' and not argp.example:
        ARGP.print_help()
        ARGP.exit(status=128, message="\nI just don't know what went wrong, maybe missing --example condition?\n")


if __name__ == '__main__':
    main()  # pragma: no cover

Example calls:

示例调用:

$ python3 ~/helloworld.py; echo $?
usage: helloworld.py [-h] [--example]

 Example argparser based python file

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

I just don't know what went wrong, maybe missing --example condition?
128
$ python3 ~/helloworld.py --example; echo $?
0

回答by radtek

Here is another way to do it, if you need something flexible where you want to display help if specific params are passed, none at all or more than 1 conflicting arg:

这是另一种方法,如果您需要一些灵活的东西,如果传递了特定参数,则希望在其中显示帮助,根本没有或超过 1 个冲突 arg:

import argparse
import sys

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--days', required=False,  help="Check mapped inventory that is x days old", default=None)
    parser.add_argument('-e', '--event', required=False, action="store", dest="event_id",
                        help="Check mapped inventory for a specific event", default=None)
    parser.add_argument('-b', '--broker', required=False, action="store", dest="broker_id",
                        help="Check mapped inventory for a broker", default=None)
    parser.add_argument('-k', '--keyword', required=False, action="store", dest="event_keyword",
                        help="Check mapped inventory for a specific event keyword", default=None)
    parser.add_argument('-p', '--product', required=False, action="store", dest="product_id",
                        help="Check mapped inventory for a specific product", default=None)
    parser.add_argument('-m', '--metadata', required=False, action="store", dest="metadata",
                        help="Check mapped inventory for specific metadata, good for debugging past tix", default=None)
    parser.add_argument('-u', '--update', required=False, action="store_true", dest="make_updates",
                        help="Update the event for a product if there is a difference, default No", default=False)
    args = parser.parse_args()

    days = args.days
    event_id = args.event_id
    broker_id = args.broker_id
    event_keyword = args.event_keyword
    product_id = args.product_id
    metadata = args.metadata
    make_updates = args.make_updates

    no_change_counter = 0
    change_counter = 0

    req_arg = bool(days) + bool(event_id) + bool(broker_id) + bool(product_id) + bool(event_keyword) + bool(metadata)
    if not req_arg:
        print("Need to specify days, broker id, event id, event keyword or past tickets full metadata")
        parser.print_help()
        sys.exit()
    elif req_arg != 1:
        print("More than one option specified. Need to specify only one required option")
        parser.print_help()
        sys.exit()

    # Processing logic here ...

Cheers!

干杯!