2017-02-24 63 views
2

我看到一個換行符沒有保存在我的EPILOG中?我想知道爲什麼如果我看到換行符只有當一行有74個字符時才保留下來?python單擊幫助格式化換行

# http://click.pocoo.org/5/commands/ 

import click, sys 

def main_caller(*args, **kwargs): 
    print('act on arguments', args, kwargs) 

EPILOG = ''' 
# oneline 
# twoline 

\n 
# oneline with 74char             x 
# twoline with 74char             x 
''' 

@click.group(help='wwwwwwwwww', epilog=EPILOG, invoke_without_command=True, chain=True) 
@click.argument('start_or_stop') 
@click.option('-v', '--verbose', default=False, help='Print Verbose messages') 
@click.option('-l', '--logfile', help='Path to logfile to store log messages') 
@click.option('-a', '--action', multiple=True, type=click.Choice(['act1', 'act2', 'act3']), default=['act1', 'act2']) 
def cli(*args, **kwargs): 
    '''foo bar''' 
    pass 

@cli.command() 
@click.option('--debug/--no-debug', default=False) 
def cmd1(*args, **kwargs): 
    print('cmd1', args, kwargs) 
    return 'cmd11111' 

@cli.command() 
@click.option('-x', '--xxx', default='x') 
def cmd2(*args, **kwargs): 
    print('cmd2', args, kwargs) 
    return 'cmd22222' 

@cli.resultcallback() 
def process_pipeline(*args, **kwargs): 
    print('process', args, kwargs) 
    print('args', sys.argv[1:])  

if __name__ == '__main__': 
    cli() 

輸出是:

/click_sandbox.py --help 
2017/02/24 19:31:43 Platform overridden to 'RHEL5_64' 
Usage: click_sandbox.py [OPTIONS] START_OR_STOP COMMAND1 [ARGS]... [COMMAND2 
         [ARGS]...]... 

    wwwwwwwwww 

Options: 
    -v, --verbose TEXT    Print Verbose messages 
    -l, --logfile TEXT    Path to logfile to store log messages 
    -a, --action [act1|act2|act3] 
    --help       Show this message and exit. 

Commands: 
    cmd1 
    cmd2 

    # oneline # twoline 

    # oneline with 74char             x 
    # twoline with 74char             x 

回答

2

你換行沒有被保存下來,因爲在結尾處理作家做自動換行。這可以用一個子類來解決,以click.Group,通過創建format_epilog()不這樣做自動換行:

class SpecialEpilog(click.Group): 
    def format_epilog(self, ctx, formatter): 
     if self.epilog: 
      formatter.write_paragraph() 
      for line in self.epilog.split('\n'): 
       formatter.write_text(line) 

# Tell click to use our epilog formatter 
@click.group(cls=SpecialEpilog, 
    help='wwwwwwwwww', epilog=EPILOG, invoke_without_command=True, chain=True) 
.... 
+0

真棒:)完美的作品。謝謝 – abarik

+0

只要EPILOG具有可打印字符,如果我只放了幾行換行符('\ n \ n \ n'),它就不起作用,除非我用可打印字符定位它們。任何想法如何修改上述以類似的方式來處理幾條換行符? – slm

+0

@slm,好問題。不是我考慮過的用例。通過框架看,答案似乎是肯定的,但它會涉及更多的覆蓋。如果你彈出一個問題,我會很樂意輸入一個答案。 –