【问题标题】:Formatted string in help of program程序帮助中的格式化字符串
【发布时间】:2022-01-03 01:32:31
【问题描述】:

我正在尝试在我的一个 python 脚本中添加描述,但输出未格式化。

def main():

    hlp_string = (""" File nomenclature:
        \t<name>_<last name>_<version>_<report_name>.<extension>\n
        \tVersion will be always NONE\n
        \tFor txt:\n
        \t\treport_name = unformatted\n
        \t\tfile_extension = txt\n
        \tFor csv:\n
        \t\treport_name = column\n
        \t\tfile_extension = csv\n
        \t\tExample:\n
        \t\tRON_DAVIS_NONE_unformatted.txt\n      
        \t\tRON_DAVIS_NONE_column.csv
        """
    )
    parser = argparse.ArgumentParser(description=hlp_string)
    parser.add_argument("-l", "--name_details", action="store", help="name_details")
    parser.add_argument(
        "-p", "--data_details", action="store", help="data_details"
    )
    args = parser.parse_args()
    if args.name_details and args.data_details:
        print("Print got argument")
    else:
        parser.print_help()

if __name__=="__main__":
        main()

一旦我运行这个得到纯文本,这既不是在输出中添加 \t 或 \n

mytest.py --help
usage: mytest.py [-h] [-l NAME_DETAILS] [-p DATA_DETAILS]

File nomenclature: <name>_<last name>_<version>_<report_name>.<extension>
Version will be always NONE For txt: report_name = unformatted file_extension
= pdf For csv: report_name = column file_extension = csv Example:
RON_DAVIS_NONE_unformatted.txt RON_DAVIS_NONE_column.csv

optional arguments:
  -h, --help            show this help message and exit
  -l NAME_DETAILS, --name_details NAME_DETAILS
                        name_details
  -p DATA_DETAILS, --data_details DATA_DETAILS
                        data_details

【问题讨论】:

  • stackoverflow.com/questions/5462873/… 有帮助吗?我发现它是argparse parser.print_help formatting 的第一个搜索结果。
  • FWIW,我发现虽然它可以很好地完成许多标准任务,但argparse 并不是最干净或设计最优雅的东西。第三方工具建议不在此处讨论,但您可以考虑四处看看。

标签: python linux python-3.6 script


【解决方案1】:

最简单的解决方案是将parser.print_help() 替换为print(hlp_string)
This 可能会回答您的问题。

【讨论】:

  • parser.print_help 在这里打印的不仅仅是hlp_string - 它还做了额外的工作来显示usage 行并整齐地格式化optional arguments,它会根据parser 自动确定自己的状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-11
相关资源
最近更新 更多