Argparse-制作输入和输出列表

时间:2018-08-16 12:49:27

标签: python argparse

Python的新手,

我的教授给了我一段代码来帮助处理某些图像,但是由于每次都需要规定输入和输出,因此一次只能处理一张图像。通常我会使用import os或glob,但是argparse对我来说是新事物,而我通常的方法不起作用。

我需要对其进行编辑,以创建一个'.hdf'文件列表,其输出与输入相同,只是名称更改为'_Processed.hdf'

下面的代码:

# Import the numpy library
import numpy
# Import the GDAL library
from osgeo import gdal
# Import the GDAL/OGR spatial reference library
from osgeo import osr
# Import the HDF4 reader.
import pyhdf.SD
# Import the system library
import sys
# Import the python Argument parser
import argparse
import pprint
import rsgislib    

def creatGCPs(lat_arr, lon_arr):

    y_size = lat_arr.shape[0]
    x_size = lat_arr.shape[1]
    print(x_size)
    print(y_size)

    gcps = []
    for y in range(y_size):
        for x in range(x_size):
            gcps.append([x, y, lon_arr[y,x], lat_arr[y,x]])
    return gcps


def run(inputFile, outputFile):   
    hdfImg = pyhdf.SD.SD(inputFile)
    #print("Available Datasets")
    pprint.pprint(hdfImg.datasets())
    #print("Get Header Attributes")
    #attr = hdfImg.attributes(full=1)
    #pprint.pprint(attr)
    rsgisUtils = rsgislib.RSGISPyUtils()
    wktStr = rsgisUtils.getWKTFromEPSGCode(4326)
    #print(wktStr)

    lat_arr = hdfImg.select('Latitude')[:]
    long_arr = hdfImg.select('Longitude')[:]    
    sel_dataset_arr = hdfImg.select('Optical_Depth_Land_And_Ocean')[:]

    gcplst = creatGCPs(lat_arr, long_arr)


    y_size = lat_arr.shape[0]
    x_size = lat_arr.shape[1]

    min_lat = numpy.min(lat_arr)
    max_lat = numpy.max(lat_arr)
    min_lon = numpy.min(long_arr)
    max_lon = numpy.max(long_arr)

    lat_res = (max_lat-min_lat)/float(y_size)
    lon_res = (max_lon-min_lon)/float(x_size)

    driver = gdal.GetDriverByName( "KEA" )
    metadata = driver.GetMetadata()
    dst_ds = driver.Create( outputFile, x_size, y_size, 1, gdal.GDT_Float32 )
    dst_ds.GetRasterBand(1).WriteArray(sel_dataset_arr)

    gcp_list = []
    for gcp_arr in gcplst:
        gcp = gdal.GCP(int(gcp_arr[2]), int(gcp_arr[3]), int(0), gcp_arr[0], gcp_arr[1])
        gcp_list.append(gcp)

    dst_ds.SetGCPs(gcp_list, wktStr)

    dst_ds = None



if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # Define the argument for specifying the input file.
    parser.add_argument("-i", "--input", type=str, required=True,  help="Specify the input image file.")
    # Define the argument for specifying the output file.
    parser.add_argument("-o", "--output", type=str, required=True, help="Specify the output image file.")
    args = parser.parse_args()


    run(args.input, args.output)

2 个答案:

答案 0 :(得分:0)

您可以使用nargs='+'选项,并且由于将只有一个必需的参数,因此建议您不要使用--input作为选项,而只需运行脚本为script_name.py input_file1 input_file2 input_file3 ...

import os.path
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('input', nargs='+', help="Specify the input image file.")
    args = parser.parse_args()
    for filename in args.input:
        root, ext = os.path.splitext(filename)
        run(filename, ''.join((root, '_Processed', ext)))

答案 1 :(得分:0)

argparse docs here,您可以简单地在参数定义中添加nargs='*'。但是,请确保输入和输出文件的顺序相同...

此外,您可以使用pathlib.Path对象,在Python> = 3.4中使用which is now standard来播放文件名。

因此,在顶部添加了from pathlib import Path,代码的最后一部分变为:

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # Define the argument for specifying the input file.
    parser.add_argument("-i", "--input", nargs='*', type=str, required=True,  help="Specify the input image file.")

    args = parser.parse_args()

    for input in args.input:
        output = Path(input).stem + '_Processed.hdf'
        run(input, output)

在这里,args.input现在是一个字符串列表,因此我们对其进行迭代。 .stem属性返回没有任何扩展名的文件名,我发现它比input[:-4]之类的文件名更干净,python this_script.py -i Image_*仅适用于特定的扩展名长度...

这与标准linux shell中的glob模式一起使用效果很好(其他情况我不知道)。

例如调用$("p").on("custom.someNamespace", function(event) { alert(event.namespace); }); $("p").click(function(event) { $(this).trigger("custom.someNamespace"); }); $("button").click(function() { $("p").off("custom.someNamespace"); }); ,处理文件名以“ Image_”开头的每个文件。