如何将参数传递给Python模块中的主函数?

How to pass arguments to main function within Python module?

我最近开始了解更多关于Python包和模块的信息。我目前正忙于更新现有模块,以便可以作为脚本运行或作为模块导入到其他代码中。我不知道如何在模块内构造输入参数并将它们传递给模块内的main()函数。

我已经编写了我的main()函数,并在传递输入参数的if_uu name_uu='uuu main_uuuu'下调用了它。输入目前是硬编码的,以显示我正在尝试实现的目标。对于如何正确地构造用户将传递的输入参数的任何帮助,都将不胜感激,这些参数随后将传递给主函数。

如前所述,当直接使用或作为模块导入到其他代码中并从中运行时,我正在尝试将以下内容用作脚本。如果我把它作为一个模块导入,在导入它时会调用main()函数吗?以下结构是否正确?我是如何写下以下内容的?感谢您的任何建议。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'''
Created on March 12, 2017

Create a new ArcHydro Schema

File Geodatabase and Rasters

Folder

@author: PeterW
'''

# import site-packages and modules
import re
from pathlib import Path
import arcpy

# set environment settings
arcpy.env.overwriteOutput = True


def archydro_rasters_folder(workspace):
   """Create rasters folder directory
    if it doens't already exist"""

    model_name = Path(workspace).name
    layers_name = re.sub(r"\D+","Layers", model_name)
    layers_folder = Path(workspace, layers_name)
    if layers_folder.exists():
        arcpy.AddMessage("Rasters folder: {0} exists".format(layers_name))
    else:
        layers_folder.mkdir(parents=True)
        arcpy.AddMessage("Rasters folder {0} created".format(layers_name))


def archydro_fgdb_schema(workspace, schema, dem):
   """Create file geodatabase using XML
    schema and set coordinate system based
    on input DEM if it doesn't already exist"""

    model_name = Path(workspace).name
    fgdb ="{0}.gdb".format(model_name)
    if arcpy.Exists(str(Path(workspace, fgdb))):
        arcpy.AddMessage("{0} file geodatabase exists".format(fgdb))
    else:
        new_fgdb = arcpy.CreateFileGDB_management(str(workspace), fgdb)
        import_type ="SCHEMA_ONLY"
        config_keyword ="DEFAULTS"
        arcpy.AddMessage("New {0} file geodatabase created".format(fgdb))
        arcpy.ImportXMLWorkspaceDocument_management(new_fgdb, schema,
                                                    import_type,
                                                    config_keyword)
        arcpy.AddMessage("ArcHydro schema imported")
        projection = arcpy.Describe(dem).spatialReference
        projection_name = projection.PCSName
        feature_dataset = Path(workspace, fgdb,"Layers")
        arcpy.DefineProjection_management(str(feature_dataset),
                                          projection)
        arcpy.AddMessage("Changed projection to {0}".format(projection_name))


def main(workspace, dem, schema):
   """main function to create rasters folder
    and file geodatabase"""

    archydro_rasters_folder(workspace)
    archydro_fgdb_schema(schema, dem, workspace)

if __name__ == '__main__':
    main(workspace = r"E:\Projects\2016\01_Bertrand_Small_Projects\G113268\ArcHydro\Model04",
         dem = r"E:\Projects\2016\01_Bertrand_Small_Projects\G113268\ArcHydro\DEM2
aw"
,
         schema = r"E:\Python\Masters\Schema\ESRI_UC12\ModelBuilder\Schema\Model01.xml")

更新日期:2013年3月17日

以下是我根据Jonathan的建议更新的python模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'''
Created on March 12, 2017

Create a new ArcHydro Schema

File Geodatabase and Rasters

Folder

@author: PeterW
'''

# import site-packages and modules
import re
from pathlib import Path
import arcpy
import argparse

# set environment settings
arcpy.env.overwriteOutput = True


def rasters_directory(workspace):
   """Create rasters folder directory
    if it doens't already exist"""

    model_name = Path(workspace).name
    layers_name = re.sub(r"\D+","Layers", model_name)
    layers_folder = Path(workspace, layers_name)
    if layers_folder.exists():
        arcpy.AddMessage("Rasters folder: {0} exists".format(layers_name))
    else:
        layers_folder.mkdir(parents=True)
        arcpy.AddMessage("Rasters folder {0} created".format(layers_name))


def fgdb_schema(workspace, schema, dem):
   """Create file geodatabase using XML
    schema and set coordinate system based
    on input DEM if it doesn't already exist"""

    model_name = Path(workspace).name
    fgdb ="{0}.gdb".format(model_name)
    if arcpy.Exists(str(Path(workspace, fgdb))):
        arcpy.AddMessage("{0} file geodatabase exists".format(fgdb))
    else:
        new_fgdb = arcpy.CreateFileGDB_management(str(workspace), fgdb)
        import_type ="SCHEMA_ONLY"
        config_keyword ="DEFAULTS"
        arcpy.AddMessage("New {0} file geodatabase created".format(fgdb))
        arcpy.ImportXMLWorkspaceDocument_management(new_fgdb, schema,
                                                    import_type,
                                                    config_keyword)
        arcpy.AddMessage("ArcHydro schema imported")
        projection = arcpy.Describe(dem).spatialReference
        projection_name = projection.PCSName
        feature_dataset = Path(workspace, fgdb,"Layers")
        arcpy.DefineProjection_management(str(feature_dataset),
                                          projection)
        arcpy.AddMessage("Changed projection to {0}".format(projection_name))


def model_schema(workspace, schema, dem):
   """Create model schema: rasters folder
    and file geodatabase"""

    rasters_directory(workspace)
    fgdb_schema(schema, dem, workspace)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Create a ArcHydro schema')
    parser.add_argument('--workspace', metavar='path', required=True,
                        help='the path to workspace')
    parser.add_argument('--schema', metavar='path', required=True,
                        help='path to schema')
    parser.add_argument('--dem', metavar='path', required=True,
                        help='path to dem')
    args = parser.parse_args()
    model_schema(workspace=args.workspace, schema=args.schema, dem=args.dem)

这对我来说是正确的,是的,如果你想把它用作一个模块,你可以导入main。不过,最好用更具描述性的方式来命名它。

阐明__main__main()的功能是如何工作的。当您执行一个模块时,它将有一个存储在__name__中的名称。如果您以脚本的形式单独执行模块,它的名称将为__main__。如果将其作为模块的一部分执行,即将其导入另一个模块,那么它将具有该模块的名称。

函数main()可以命名任何您想命名的东西,这不会影响您的程序。在小脚本中,它通常被命名为main,但如果它是更大代码体的一部分,则不是一个特别好的名称。

在允许用户在作为脚本运行时输入参数方面,我将研究使用argparseclick

argparse如何工作的示例。

1
2
3
4
5
6
7
8
9
10
11
12
if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Create a ArcHydro schema')
    parser.add_argument('--workspace', metavar='path', required=True,
                        help='the path to workspace')
    parser.add_argument('--schema', metavar='path', required=True,
                        help='path to schema')
    parser.add_argument('--dem', metavar='path', required=True,
                        help='path to dem')
    args = parser.parse_args()
    main(workspace=args.workspace, schema=args.schema, dem=args.dem)