Python 通过命令行参数显示帮助

Python 通过命令行参数显示帮助,python,Python,我有一个通过命令行参数运行的python程序。我使用了sys模块 下面是我的test.pyPython文件,其中包含所有参数: if len(sys.argv) > 1: files = sys.argv get_input(files) get\u input方法位于另一个Python文件中,我在其中定义了选项 options = { '--case1': case1, '--case2': case2, } def get_input(argumen

我有一个通过命令行参数运行的python程序。我使用了
sys
模块

下面是我的
test.py
Python文件,其中包含所有参数:

if len(sys.argv) > 1:
    files = sys.argv

get_input(files)
get\u input
方法位于另一个Python文件中,我在其中定义了
选项

options = {

    '--case1': case1,
    '--case2': case2,

}


def get_input(arguments):

    for file in arguments[1:]:
        if file in options:
            options[file]()
        else:
            invalid_input(file)
要运行:

python test.py --case1 --case2
我的意图是,我想向用户显示所有命令,以防他们需要阅读文档

他们应该能够像阅读帮助的所有包一样阅读所有命令,
python test.py--help
。有了这个,他们应该能够查看所有可以运行的命令


如何执行此操作?

您好,您可以使用选项分析器添加选项和相关帮助信息

默认情况下,它具有“帮助”选项,显示您添加的所有可用选项

详细文件如下所示。下面是一个例子

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

Python开发人员可以引以为傲的最佳品质之一是使用内置库而不是自定义库。因此,让我们使用:

现在可以使用cmd参数,如
python myscript.py--case1

这带有一个默认的
--help
参数,您现在可以使用它,比如:
python myscript.py--help
,它将输出:

usage: myscript.py [-h] [--case1] [--case2]

My application description

optional arguments:
  -h, --help  show this help message and exit
  --case1     It does something
  --case2     It does something else, I guess

为什么不使用
argparse
?大多数搜索都给了我sys.argv。所以说:)谢谢克里斯·兰兹。我正在浏览
argparse
,并认为这是我应该使用的。
optparse
自Python 3.2以来就被弃用了。对于新代码,请改用
argparse
。谢谢。这似乎是一个恰当的选择:)@themaster cool,小心我刚刚修复了示例代码中的一个拼写错误;)
usage: myscript.py [-h] [--case1] [--case2]

My application description

optional arguments:
  -h, --help  show this help message and exit
  --case1     It does something
  --case2     It does something else, I guess