简体   繁体   English

正确包装长python字符串以进行optparse

[英]Wrap long python strings correctly for optparse

How can I automatically wrap long python strings so that they print correctly? 如何自动换行长python字符串以便正确打印?

Specifically, I am trying to add help strings with optparse which I want to be able to modify easily. 具体来说,我正在尝试使用optparse添加帮助字符串,我希望能够轻松修改。

I have found several methods of dealing with long strings, none of which allow me to refill after making changes using Mq in emacs or similar: 我找到了几种处理长字符串的方法,在emacs或类似代码中使用Mq进行更改后,所有这些方法都不允许我重新填充:

p.add_option('-a', help = "this is my\
                           long help text")

forces newlines in the result and doesn't allow refilling 强制结果中的换行符,不允许重新填充

p.add_option('-a', help = "this is my "
                          "long help text")

formats correctly but doesn't allow refilling 格式正确但不允许重新填充

p.add_option('-a', help = '''
             this is my
             long help text
             ''')

formats incorrectly but does allow refilling 格式不正确,但允许重新填充

p.add_option('-a', help = dedent('''
             this is my
             long help text
             '''))

is the best option I've found, formats almost correctly and allows refilling but results in an additional space at the beginning of the string. 是我发现的最佳选择,格式几乎正确并允许重新填充,但会在字符串的开头产生额外的空间。

The docs use dedent so it seems reasonable, especially if it works. 文档使用dedent所以它似乎是合理的,特别是如果它工作。 If you want to drop the leading space you could: 如果你想放弃领先的空间,你可以:

help = dedent('''
             this is my
             long help text
             ''')[1:]

although 虽然

dedent(…).lstrip() 

might be more obvious. 可能更明显。

I'm not 100% sure what refilling is, but here's what I typically use: 我不是100%确定加油是什么,但这是我通常使用的:

p.add_option('-a', help = ("this is my "
                           "long help text"))

(note the additional parenthesis). (注意附加括号)。 Emacs lines up the next line with the previous open parenthesis for me. Emacs为我提供了前一个左括号的下一行。

Use argparse instead of optparse, if you are using Python >= 2.7. 如果使用的是Python> = 2.7,请使用argparse而不是optparse。 It does dedent for you. dedent你。 You can just do: 你可以这样做:

parser.add_argument('--argument', '-a', help='''
    this is my
    long help text
    ''')

Even if you are using Python < 2.7, you can install argparse from pypi. 即使您使用的是Python <2.7,也可以从pypi安装argparse。

Note that there is a way to suppress this auto-dedent behavior. 请注意,有一种方法可以抑制这种自动行为。 The link given by @msw is actually the section about it. @msw给出的链接实际上是关于它的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM