Python 2.7中ArgumentParser中的多行参数帮助行

时间:2019-04-16 04:37:44

标签: python python-2.7

我有一个代码,其中包含一些参数,如下所示:

parser = argparse.ArgumentParser()
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('--input_feed', help='''Please provide an input csv file for automatic database creation such as follow: \n environment, database_name, location \n
 ENV, d_wc_wrk_pic, '/data/dev/wc/storage/work/d_wc_wrk_pic'
 ''',required=True)
args = parser.parse_args()

stdout的输出如下:

stdout output

当我键入--help命令时,提示后面没有换行吗?有人可以建议我解决此新行错误的方法吗?

1 个答案:

答案 0 :(得分:0)

argparse模块中,类HelpFormatter中有一个方法:

def _split_lines(self, text, width):
    text = self._whitespace_matcher.sub(' ', text).strip()
    # The textwrap module is used only for formatting help.
    # Delay its import for speeding up the common usage of argparse.
    import textwrap
    return textwrap.wrap(text, width)

尽管您的帮助消息中包含新行,但是_split_lines方法将它们替换为空格,然后使用textwrap模块再次将行拆分。

为避免直接修改argparse模块的代码,可以使用称为注入的技巧:

import argparse


def inject_help_formatter():
    def _my_split_lines(self, text, width):
        return text.split('\n')

    # Inject
    argparse.HelpFormatter._split_lines = _my_split_lines

# Do inject before `parser.parse_args()`
inject_help_formatter()

parser = argparse.ArgumentParser()
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('--input_feed', help='''Please provide an input csv file for automatic database creation such as follow: 
environment, database_name, location
 ENV, d_wc_wrk_pic, '/data/dev/wc/storage/work/d_wc_wrk_pic'
 ''', required=True)
args = parser.parse_args()

--help输出:

optional arguments:
  -h, --help            show this help message and exit

required named arguments:
  --input_feed INPUT_FEED
                        Please provide an input csv file for automatic database creation such as follow: 
                        environment, database_name, location
                         ENV, d_wc_wrk_pic, '/data/dev/wc/storage/work/d_wc_wrk_pic'