设为首页 收藏本站
查看: 389|回复: 0

[经验分享] ArcGIS9.2中使用Python和GP交互

[复制链接]

尚未签到

发表于 2015-4-28 08:10:40 | 显示全部楼层 |阅读模式
  下面是ArcGIS9.2帮助中对如何使用Python和GP操作交互的说明。
  另外可参考Mars的自语的《ArcGIS 9.2 笔记(5):Georocessing与Python》  http://www.iyunv.com/maweifeng/archive/2007/01/10/616329.html

  Creating a new Python script module


   About creating a new Python script module

  To retain Python code, Python files (.py extension) can be created. These files are ASCII files that contain Python statements.
  Learn more about executing and debugging Python
   How to create a new Python script module

  • In PythonWin, click the File menu and click New. Accept the default option of Python Script and click OK.  The Script1 window will open. Script1 is the default name of your script.
  • Click the Maximize button on the Script1 window.
  • Click the File menu and click Save As. Name the script multi_clip and save it in a folder of your choice.  Modules should follow the same naming rules as variables. They must start with a letter and can be followed by any number of letters, digits, or underscores. Module names become variable names when they are imported, so to avoid syntax errors, they should not use reserved words such as while or if. Scripts should always have a .py extension, as this is required when importing a script module. It also defines Python as the executing application for your script.
  • At the top of your script add the following lines:
    #Import modules
    import arcgisscripting, sys, os


      This imports the system, operating system, and arcgisscripting modules to the script. The arcgisscripting module has already been discussed, but the other two are new.

    • The sys module refers to the Python system and will be used to access user-specified inputs.
    • The os module provides easy access to the most fundamental tools of the operating system. Some of the os module's file name manipulation tools are used in this script.
      Refer to your Python reference material for more information about the tools in these modules.

  • Add the following code to declare the geoprocessor object:
    #Create the geoprocessor object
    gp = arcgisscripting.create()


      This script will have the following arguments so it can be used in a generic fashion:

    • An input workspace defining the set of feature classes to process
    • A feature class to be used by the Clip tool as the area to be clipped from an input feature class
    • An output workspace where the results of the Clip tool will be written
    • A cluster tolerance that will be used by the Clip tool  Refer to the Clip tool in the Analysis toolbox for detailed information on how Clip works.

  • Add the following code to your script to define and set variables based on the user-defined values passed to the script at execution:
    #Set the input workspace
    gp.workspace = sys.argv[1]
    #Set the clip featureclass
    clipFeatures = sys.argv[2]
    #Set the output workspace
    outWorkspace = sys.argv[3]
    #Set the cluster tolerance
    clusterTolerance = sys.argv[4]

      The passed-in arguments are attributes of the sys module and can be sliced to extract the argument you want. The first value of argv, argv[0], is the name of the script. You can apply the same slicing tools used on strings to the argv attribute, so sys.argv[1:] will return the entire list of argument values.
  • Add the following error-handling statement and geoprocessor call to the script window:
    try:
    #Get a list of the featureclasses in the input folder
    fcs = gp.ListFeatureClasses()


      Python enforces indentation of code after certain statements as a construct of the language. The try statement defines the beginning of a block of code that will be handled by its associated exception handler, or except statement. All code within this block must be indented. Python uses try/except blocks to handle unexpected errors during execution. Exception handlers define what the program should do when an exception is raised by the system or by the script itself. In this case, you are only concerned about an error occurring with the geoprocessor, so a try block is started just before you start to use the object. It is good practice to use exception handling in any script using the geoprocessor so its error messages can be propagated back to the user. This also allows the script to exit gracefully and return informative messages instead of simply causing a system error.  The geoprocessor's ListFeatureClasses method returns an enumeration of feature class names in the current workspace. The workspace defines the location of your data and where all new data will be created unless a full path is specified. The workspace has already been set to the first argument's value.
  • Add the following code to get the first value of the enumeration:
    #Loop through the list of feature classes
    fcs.Reset()
    fc = fcs.Next()

      An enumeration is a list that has an undefined number of items. It should always be reset before the first item is extracted so you can get the first item in the list. You want to get the first item before you start looping through its contents, as you will use it as the conditional value for continuing a loop.
  • Add the following code:
    while fc:   
    #Validate the new feature class name for the output workspace.
    outFeatureClass = outWorkspace + "/" + gp.ValidateTableName(fc, outWorkspace)
    #Clip each feature class in the list with the clip feature class.
    #Do not clip the clipFeatures, it may be in the same workspace.
    if str(fc) != str(os.path.split(clipFeatures)[1]):
    gp.Clip(fc, clipFeatures, outFeatureClass, clusterTolerance)
    fc = fcs.Next()


      When there are no more names in the enumeration, a null or empty string will be returned. Python will evaluate this as false, which will cause the while loop to exit. The next value from the enumeration must be retrieved before the end of the indented block so it is evaluated correctly at the start of the loop. The ValidateTableName method is used to ensure the output name is valid for the output workspace. Certain characters, such as periods or dashes, are not allowed in geodatabases, so this method will return a name with valid characters in place of invalid ones. It will also return a unique name so no existing data is overwritten.  The os module's path object is used to manipulate the clip feature classes path, so only the feature class name is evaluated in an expression, not the entire path. The Clip tool is accessed as a method of the geoproccessor, using the various string variables as parameter values.
  • Add the following lines to complete the script:
    except:
    gp.AddMessage(gp.GetMessages(2))
    print gp.GetMessages(2)


      View the completed script  The except statement is required by the earlier try statement; otherwise, a syntax error will occur. If an error occurs during execution, the code within the except block will be executed. In this case, any message with a severity value of 2, indicating an error, will be added to the geoprocessor in case the script is used as the source of a tool. All error messages are also printed to the standard output in case the script is run outside a tool.
  • Save the script by clicking the Save button on the Standard toolbar.
  • Add the following comments to the top of your script:
    ##Script Name: Clip Multiple Feature Classes
    ##Description: Clips one or more shapefiles
    ##from a folder and places the clipped
    ##feature classes into a geodatabase.
    ##Created By: Insert name here.
    ##Date: Insert date here.

      The script completed above is used to learn more about using Python, with Executing and debugging Python, and Setting breakpoints using Python.

Tips


  • When naming variables, remember that Python is case sensitive, so "GP" is not the same as "gp". The names of the geoprocessor's methods and properties (including tool and environment setting names) are not case sensitive.
  • Python automatically removes an object from memory when it is no longer referenced in a program. When a script completes, all memory allocated for objects is released and any open files are closed. The del statement can be used to delete an object so its memory is deallocated during a script's execution.
  • Many geoprocessing scripts are not generic in nature and have no arguments. They use defined dataset names and parameter values and may not require the sys module. Import modules only as needed to avoid unnecessary memory use.
  • Statements that end with a colon indicate the beginning of indented code. Python does not use braces, brackets, or semicolons to indicate the beginning or end of a block of code. Instead Python, uses the indentation of the block to define its boundaries. This results in code that is easy to read and write.

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-61337-1-1.html 上篇帖子: Python 模块学习:os模块 下篇帖子: python 模板
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表