首页 > 解决方案 > 退格 \n \t 在长字符串 python argparse 中不起作用

问题描述

我有以下代码,我在其中添加了工具的描述

usage = r"""
\n-------------------------------------------
Serial Chain Processing\n \
 \n--------------------------------------------

\nSteps. 

1. Buffers to 500 m a shapefile containing the country boundaries in EPSG: 3035 
projection.\n 
2. Clip a continental mask (DLT, GRA, or TCD), to the country boundaries (EPSG:3035)\n
3. Reproject the raster from step 2 to the National Grid using a WKT file 
with the translation parameters.\n 
4. Use the raster calculator to correct the outside areas using the 
following calculation: 

\n\tif(a==1){
    \n\t\toutput=b;
\n\t}
\n\tif(a==0){
    \n\t\toutput = a;
\n\t}
\n\tif(a==1&&IsNoData(b)){
    \n\t\toutput=0;
\n\t}
\n\tif(a==1&&b==255){
    \n\t\toutput=0;
\n}
\n\tif(a==0){
    \n\t\toutput=255;
\n\t}

\nBeing
\n\ta == Binary country boundaries raster in National projection
\n\tb == Raster from Step 3.

\n5. Check for compression, no data, pyramids and create raster attribute table,
as well as the color maps. 
"""

import glob
import subprocess
import os
import gdal 
import osr
import ogr 
import argparse
from osgeo import gdal,osr

def dir_path(string):
    if os.path.isdir(string):
        return string 
    else:
        raise NotADirectoryError(string)

def main(mask, country_bound_LAEA, country_bound_NAT):

    """Initializes the workflow."""
    pass 


if __name__ == "__main__":

    parser = argparse.ArgumentParser(description=usage)
    parser.add_argument('--mask',metavar="", type=dir_path, help = "National Product in LAEA")
    parser.add_argument('--country_bound_LAEA',metavar="", type=dir_path, help = "Country national boundaries in LAEA - Shapefile")
    parser.add_argument('--WKT_file',metavar="", type=dir_path, help = "WKT File derived from the national boundaries raster")
    parser.add_argument('--country_bound_NAT',metavar="", type=dir_path, help = "National Boundaries, binary raster dataset")
    parser.parse_args()
    #main(mask, country_bound_LAEA, country_bound_NAT)

当我运行 python -h 时,它会打印存储在 中的描述usage,但是\n\t不能跳到下一行和同一行中的制表符,以使描述更清晰一些。我不知道如何解决这个问题。我认为在过去,我使用 increment 添加了越来越多的字符串+,但是这很烦人,因为描述有几行长。

标签: pythonstringargparse

解决方案


来自argparse 文档

使用 .制作多行字符串时不需要任何特殊的转义字符"""。你也不需要r前面的""". 您需要做的就是formatter_class向 argparse 提供一个,如下所示:

parser = argparse.ArgumentParser(description=usage, formatter_class=argparse.RawDescriptionHelpFormatter)

这应该使它能够准确地打印它在您的代码中的外观。


推荐阅读