完全自定义的 Python 帮助用法 [英] Fully customized Python Help Usage

查看:26
本文介绍了完全自定义的 Python 帮助用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 创建一个完全自定义的帮助"用法(我计划将其导入到许多我希望具有样式一致性的程序中),但遇到了一些问题.

I'm trying to create a fully customized "help" usage with Python (which I plan to import into many programs that I want to have style consistency) but am having some trouble.

  1. 我不知道为什么我的描述忽略了换行符...试过 "" 和 '',
  2. 我无法让 ":" 出现在 "...ARGS" 行的/newline 之后,显然它们看起来很奇怪,坐在自己的行上,并且
  3. 我不知道如何在末尾添加换行符.请帮忙??

这是我现在得到的示例:

Here's a sample of what I am getting right now:

nameconstant version 1.0

USAGE:  myprog.py [constant text] <input.ext> <input.ext>

several lines of text describing my program.. because it will be necessary

___________________
COMPULSORY ARGS:
  input.ext
  output.ext

___________________
OPTIONAL ARGS:
  -v, --verbose  print debugging messages to terminal
  -h, --help

这就是我想要的样子:

nameconstant version 1.0

USAGE:  myprog.py [constant text] <input.ext> <input.ext>

several lines of text
describing my program..

because it will be necessary

___________________
COMPULSORY ARGS:

  input.ext
  output.ext

___________________
OPTIONAL ARGS:

  -v, --verbose      print debugging messages to terminal
  -h, --help
\n - not visible!

这是我目前使用的代码:

Here's the code I have working so far:

#!/usr/bin/env python
import argparse
import sys 
from os import path
version = "1.0"

prog = path.basename(sys.argv[0])

class USAGEformat(argparse.HelpFormatter):
        def add_usage(self, usage, actions, groups, prefix=None):
                if prefix is None:
                        prefix = 'nameconstant version '+ version+'\n\nUSAGE:  '+prog
                return super(USAGEformat, self).add_usage(
                      usage, actions, groups, prefix)

parser = argparse.ArgumentParser(add_help=False, formatter_class=USAGEformat, description='several lines of text\ndescribing my program..\n\nb
ecause it will be necessary', usage=' [optional args] <INPUT.ext> <OUTPUT.ext>')

parser._positionals.title = '___________________\nCOMPULSORY ARGS'
parser._optionals.title = '___________________\nOPTIONAL ARGS'

parser.add_argument('input', metavar="input.ext", type=argparse.FileType('rt'))
parser.add_argument('output', metavar="output.ext", type=argparse.FileType('wt'))
parser.add_argument('-v', '--verbose', action='store_true', default=False, help='print debugging messages to terminal')
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS)

接下来我应该采取什么不同的方式或研究什么??谢谢!非常感谢任何帮助.. 我是 Python 新手.

What should I be doing differently or looking into next?? Thank you! Any help is greatly appreciated.. I am new to Python.

推荐答案

import argparse
version = "1.0"

class USAGEformat(argparse.RawDescriptionHelpFormatter):
    def add_usage(self, usage, actions, groups, prefix=None):
        if prefix is None:
            prefix = 'nameconstant version '+ version+' USAGE:  '
            return super(USAGEformat, self).add_usage(
                usage, actions, groups, prefix)

parser = argparse.ArgumentParser(add_help=False, formatter_class=USAGEformat,
   description=\
'''several lines of text
describing my program..

because it will be necessary''')

gp1 = parser.add_argument_group('___________________\nCOMPULSORY ARGS')
gp1.add_argument('input', metavar="input.ext", type=argparse.FileType('rt'))
gp1.add_argument('output', metavar="output.ext", type=argparse.FileType('wt'))

gp2 = parser.add_argument_group('___________________\nOPTIONAL ARGS')
gp2.add_argument('-v', '--verbose', action='store_true', default=False,
      help='print debugging messages to terminal')
gp2.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS)

parser.print_help()

生产

2156:~/mypy$ python stack47118098.py 
nameconstant version 1.0 USAGE:  stack47118098.py [-v] [-h]
                                                  input.ext output.ext

several lines of text
describing my program..

because it will be necessary

___________________
COMPULSORY ARGS:
  input.ext
  output.ext

___________________
OPTIONAL ARGS:
  -v, --verbose  print debugging messages to terminal
  -h, --help

RawDescriptionHelpFormatter 保留描述的格式.

我使用 '''...''' 来描述只是为了让代码看起来更好;这不重要.

I used the '''...''' for the description just to make the code look nicer; that's not important.

我用 argument_groups 替换了您对现有组的重命名.你的方法很好,但我认为我的方法是开发者想要的.

I substituted argument_groups for your renaming of the existing groups. Your way works fine, but I think mine is what the developers intended.

HelpFormatter 格式化各个部分,在它们之间大量使用 \n ,然后最终去除重复项(包括结尾).所以我们必须识别和修改相关方法(format_help).

HelpFormatter formats the various pieces, with a generous use of \n between them, and then ends up stripping out duplicates (including the end). So we'd have to identify and modify the relevant method (format_help).

自从我开始回答以来,您对 usage 行进行了一些更改.

You've made some changes on the usage line since I started my answer.

我同意这样的评论,即按照惯例,需要的参数不带 [].

I agree with the comment that required arguments are shown, by convention, without the [].

我得到这个用法是因为带有前缀的行太长了.所以它拆分它,并将位置放在第二行,与选项对齐:

I got this usage because the line, with prefix, is too long. So it split it, and put the positionals on a second line, lined up with the optionals:

nameconstant version 1.0 USAGE:  stack47118098.py [-v] [-h]
                                                  input.ext output.ext

如果我设置

prefix = 'USAGE:  '

那么用法是

USAGE:  stack47118098.py [-v] [-h] input.ext output.ext

我们必须看看它是如何包装和缩进的,以使用法符合您的规范.

We'd have to look at how it does wrapping and indenting to get the usage to your specs.

导入自定义 python 模块中..为什么只有某些元素可以结转?

我解释说,每次您请求帮助或使用时,帮助格式化程序都是新创建的.定义 parser 设置格式化程序类,但不创建格式化程序.这意味着格式化程序类使用的任何全局变量都将在运行时而不是设置时获得它们的值.

I explain that the help formatter is created fresh each time you ask for a help or usage. Defining the parser sets the formatter class, but does not create a formatter. That means that any global variables that the formatter class uses will get their values as runtime rather than setup.

例如,version 是全局的(对模块而言).它最初是1.0",这是出现在用法中的值.但是如果我添加到上述脚本的末尾:

For example, version is global (to the module). It is initially '1.0' and this is the value that appears in the usage. But if I add to the end of the above script:

version = '2.0'
parser.print_help()

用法行更改为:

nameconstant version 2.0 USAGE:  stack47118098.py [-v] [-h]
                                                  input.ext output.ext

如果我使用以下命令导入此脚本:

If I import this script with:

import stack47118098 as pp

print('===========')
print(pp.version)
print(pp.parser)
pp.parser.print_help()

pp.version = '3.0'
pp.parser.print_help()

第一个帮助(导入后)使用文件中的2.0"版本.但是第二个帮助使用新定义的version.

the first help (after import) uses the '2.0' version that was in the file. But the second help uses the newly defined version.

要更改解析器的 description 之类的内容,我必须使用

To change something like the description of the parser, I have to use

pp.parser.description = 'New short description'

也就是说,我正在修改现有对象的一个​​属性.

That is, I'm modifying an attribute of the existing object.

这篇关于完全自定义的 Python 帮助用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆