optparse描述中的ASCII艺术

15 投票
3 回答
2402 浏览
提问于 2025-04-16 03:09

我正在用optparse模块写一个shell脚本,纯粹是为了好玩,所以我想在描述的地方打印一个漂亮的ASCII画。

结果这段代码:

parser = optparse.OptionParser(
    prog='./spill.py',
    description=u'''
  /     \                                     
  vvvvvvv  /|__/|                             
      I   /O,O   |                            
      I /_____   |      /|/|                 
     J|/^ ^ ^ \  |    /00  |    _//|          
      |^ ^ ^ ^ |W|   |/^^\ |   /oo |         
       \m___m__|_|    \m_m_|   \mm_|         
''',
    epilog='''
        Las cucarachas lograron con exito su plan, echando a los pestilentes sangre caliente de sus cajas de cemento. 
Ahora el hombre es una especie errante en el espacio, un vagabundo errante en las estrellas.''')

显示成这样:

$ ./bin/spill.py -h
Usage: ./spill.py [options]

   /     \                                        vvvvvvv  /|__/|
I   /O,O   |                                   I /_____   |      /|/|
J|/^ ^ ^ \  |    /00  |    _//|                 |^ ^ ^ ^ |W|   |/^^\ |   /oo |
\m___m__|_|    \m_m_|   \mm_|

Options:
  -h, --help            show this help message and exit
#.... bla bla bla, etc

我尝试了不同组合的斜杠、换行和空格,但都没有成功。

你能帮我把龙猫显示得正确一点吗,亲爱的Python爱好者?

3 个回答

0

如果其他方法都不行,那就试试代码生成吧。

最简单的方法就是先创建一个文本文件,里面写上你想要的内容,然后把这个文件用base64编码,接着把它放进一个.py文件里,并设置一个全局变量。

接下来,你只需要引入这个生成的.py文件,进行base64解码,然后打印出这个全局变量,整个过程就能顺利运行了。

9

抱歉打扰了这个老话题,不过对于那些升级到2.7版本的人来说,现在你可以很简单地在描述中显示ASCII艺术,只需要把

formatter_class=argparse.RawDescriptionHelpFormatter

传递给argparse.ArgumentParser()就可以了。

想要了解更多例子,可以查看这个链接:http://docs.python.org/2/library/argparse.html#formatter-class

11

默认的格式化工具是 IndentedHelpFormatter,它会调用这个方法:

 def format_description(self, description):
    if description:
        return self._format_text(description) + "\n"
    else:
        return ""

如果你创建一个 IndentedHelpFormatter 的子类,你可以去掉导致问题的 self._format_text 调用:

import optparse

class PlainHelpFormatter(optparse.IndentedHelpFormatter): 
    def format_description(self, description):
        if description:
            return description + "\n"
        else:
            return ""

parser = optparse.OptionParser(
    prog='./spill.py',
    formatter=PlainHelpFormatter(),
    description=u'''
  /     \                                     
  vvvvvvv  /|__/|                             
      I   /O,O   |                            
      I /_____   |      /|/|                 
     J|/^ ^ ^ \  |    /00  |    _//|          
      |^ ^ ^ ^ |W|   |/^^\ |   /oo |         
       \m___m__|_|    \m_m_|   \mm_|         
''',
    epilog='''
        Las cucarachas lograron con exito su plan, echando a los pestilentes sangre caliente de sus cajas de cemento. 
Ahora el hombre es una especie errante en el espacio, un vagabundo errante en las estrellas.''')
(opt,args) = parser.parse_args()

撰写回答