Python2.7 ArgumentParser中的多行参数帮助行

2024-09-27 23:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,它包含以下参数:

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 output

当我键入--help命令时,提示后面没有新行吗?有人能给我建议一个方法来修正这个新行错误吗?你知道吗


Tags: 代码addparserinput参数requiredargparsehelp
1条回答
网友
1楼 · 发布于 2024-09-27 23:27:31

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模块再次拆分行。你知道吗

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

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'

相关问题 更多 >

    热门问题