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

查看:41
本文介绍了完全定制的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. 我不知道如何在末尾添加换行符.请帮忙??
  1. I don't know why my description is ignoring newlines... tried "" and '',
  2. I can't get the ":" to occur after a /newline for the "...ARGS" lines, and obviously they look weird sitting on their own lines, and
  3. I have no idea how to add the newline at the end. Help please??

以下是我现在得到的示例:

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天全站免登陆