Hướng dẫn how do you pass a parameter to the main method in python? - làm thế nào để bạn truyền một tham số cho phương thức chính trong python?

Gần đây tôi đã bắt đầu tìm hiểu thêm về các gói và mô -đun Python. Tôi hiện đang bận cập nhật các mô -đun hiện có của mình để có thể chạy dưới dạng tập lệnh hoặc được nhập dưới dạng mô -đun vào mã khác của tôi. Tôi không chắc làm thế nào để xây dựng các đối số đầu vào của mình trong mô -đun của tôi và chuyển chúng đến hàm chính () trong mô -đun của tôi.

Tôi đã viết hàm Main () của tôi và gọi nó theo nếu __name__ == '__main__' chuyển các đối số đầu vào. Các đầu vào hiện được mã hóa cứng để hiển thị những gì tôi đang cố gắng đạt được. Bất kỳ trợ giúp nào trong cách xây dựng chính xác các đối số đầu vào của tôi mà người dùng sẽ vượt qua, sau đó sẽ được truyền vào chức năng chính sẽ được đánh giá cao.main() function and called it under if __name__ == '__main__' passing the input arguments. The inputs are currently hard coded to show what I'm trying to achieve. Any help in how to correctly construct my input arguments that the user will pass, which will then be passed onto the main function will be appreciated.

Như đã đề cập, tôi đang cố gắng sử dụng các mục sau làm tập lệnh khi được sử dụng trực tiếp hoặc nhập làm mô -đun vào mã khác của tôi và chạy từ đó. Nếu tôi nhập nó dưới dạng mô -đun, tôi sẽ gọi hàm chính () khi nhập nó? Cấu trúc sau đây có đúng trong cách tôi đã viết như sau không? Bất kỳ lời khuyên được đánh giá cao.main() function when importing it? Is the following structure correct in how I have written the following? Any advice is appreciated.

'''
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\raw",
         schema = r"E:\Python\Masters\Schema\ESRI_UC12\ModelBuilder\Schema\Model01.xml")

Cập nhật: 17/03/13

Sau đây là mô -đun Python cập nhật của tôi dựa trên các đề xuất của Jonathan:

'''
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)

Làm thế nào để bạn chuyển một tham số cho chức năng chính trong Python?

Các chức năng trong Python được tạo và biểu thị bằng từ khóa DEF theo sau là một tên hàm. Ví dụ: greet_customer theo sau là một tập hợp dấu ngoặc đơn (). Các tham số của hàm được lưu trữ trong dấu ngoặc đơn.. For example, greet_customer followed by a set of parentheses () . The parameters of the function are stored in the parentheses.

Chúng ta có thể chuyển tham số cho chức năng chính không?

Có, chúng ta có thể đưa ra các đối số trong hàm chính ().Các đối số dòng lệnh trong C được chỉ định sau tên của chương trình trong dòng lệnh của hệ thống và các giá trị đối số này được truyền vào chương trình của bạn trong quá trình thực hiện chương trình.ARGC và ARGV là hai đối số có thể chuyển sang chức năng chính.. Command line arguments in C are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution. The argc and argv are the two arguments that can pass to main function.

__ Main __ trong Python là gì?

__main__ là tên của môi trường nơi chạy mã cấp cao nhất.Mã cấp cao nhất là mô-đun Python do người dùng chỉ định đầu tiên bắt đầu chạy.Đó là cấp độ hàng đầu vì nó nhập tất cả các mô-đun khác mà chương trình cần.Đôi khi, mã cấp cao nhất mã hóa được gọi là điểm nhập vào ứng dụng.the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It's “top-level” because it imports all other modules that the program needs. Sometimes “top-level code” is called an entry point to the application.

Hàm chính () trong Python là gì?

Chức năng chính trong Python đóng vai trò là điểm thực hiện cho bất kỳ chương trình nào.Xác định chức năng chính trong lập trình Python là một điều cần thiết để bắt đầu thực hiện chương trình vì nó chỉ được thực thi khi chương trình được chạy trực tiếp và không được thực thi khi được nhập dưới dạng mô -đun.acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.