Document directory
- Location of the python search Module
- Share Python Module
Technology for sharing Python scripts
ArcGIS 10
The following describes the technologies you can use to share Python scripts with other users.
Search for data relative to the script location
For existing data that is not transmitted in the form of parameters, your script may need to use its path (the programmer calls it a hard connection path ). For example, you may need to set the Symbolic System attribute of the output parameter to an existing layer file or crop the data to a known dataset.
When sharing a tool with other users, make sure that the script can find the required data. Therefore, we recommend that you use the toolshare folder structure. You can place project data and scripts in the tooldata and scripts folders respectively. If this method is used, you can always find data relative to the script location.
When running a script, you can find the path of the script as follows:
scriptPath = sys.path[0]
Once this location is known, you can find the project data corresponding to this location. The following code snippet demonstrates this example:
import arcpyimport osimport sys# Get the pathname to this script#scriptPath = sys.path[0]arcpy.AddMessage("Script folder: " + scriptPath)# Get the pathname to the ToolShare folder#toolSharePath = os.path.dirname(scriptPath)arcpy.AddMessage("ToolShare folder: " + toolSharePath)# Now construct pathname to the ToolData folder#toolDataPath = os.path.join(toolSharePath, "ToolData")arcpy.AddMessage("ToolData folder: " + toolDataPath)# Create the pathname to the parks feature class found in the ToolData folder#parkPath = os.path.join(toolDataPath, "Project.gdb/Parks")arcpy.AddMessage("Parks feature class: " + parkPath)
Note:
If the script code is embedded, SYS. path [0] returns the location of the Toolbox (that is, the location of the Code ).
Find temporary Workspace
If you want to create temporary data in the script, you need a temporary workspace to create and subsequently delete temporary data.
Note:
- You must have the write permission for this workspace.
- IfWhen using a temporary workspace's geographic processing environment, you must assume that you have set it to a writable location. For the geographic processing service running on the ArcGIS Server, the ArcGIS Server automatically sets the temporary workspace as a specific folder to be written.
- Exercise caution when using the current workspace environment as a temporary workspace. The current environment may be a remote database, and you never want to use a remote database as a temporary location, because communication with a remote database is costly, you cannot quickly create, write, and delete temporary data.
- IfWeiTo set a temporary workspace, you need to find a writable location. In this case, you can select the following methods:
- If the toolshare folder structure is used, you can use Scratch. GDB in the scratch folder. If you are using error-proof programming, check whether scratch. GDB exists because the user may have deleted it.
- If a script parameter is an output dataset (such as a feature class), you can determine that you have write permission on the location of the output dataset and use it as a temporary workspace. However, you need to check whether the location is a feature dataset or a remote database. (As mentioned above, you never want to use a remote database as a temporary location. Because communication with a remote database is costly, you cannot quickly create, write, and delete temporary data .)
- When all other methods fail, you can always use the temp directory of the system.
- The size of the element classes in the shapefile and personal geographic database workspace cannot exceed 2 GB. Although 2 GB can accommodate a lot of data, this is still a limiting factor. The default size of a file-based geographic database workspace for a dataset is 1 MB (1024 GB ). If you think the size of the temporary dataset may exceed 2 GB, use the File geographic database as the temporary workspace.
- UseThe createscratchname function creates a unique dataset name in a temporary workspace.
The following code example shows code execution for searching for a temporary workspace, which is highly error-tolerant. This Code
- If you do not use the current workspace as a temporary workspace, it is easy to modify it.
- Assume that you use the toolshare folder structure
- Try to find and use the file geographic database, and do not use the shapefile workspace unless necessary
import arcpyfrom arcpy import envimport sysimport osdef getScratchWorkspace(outDataset): # outDataSet is assumed to be the full pathname to a dataset. Typically, # this would be a tool's output parameter value. # # Get the scratch workspace environment. If it's set, just return it. # scratchWS = env.scratchWorkspace if scratchWS: return scratchWS # Let's go fishing... # # If you're using the ToolShare folder structure, look for scratch.gdb in # the Scratch folder. # scriptPath = sys.path[0] toolSharePath = os.path.dirname(scriptPath) scratchWS = os.path.join(toolSharePath, "Scratch/scratch.gdb") if not arcpy.Exists(scratchWS): scratchWS = "" # No scratch workspace environment and no scratch.gdb in the ToolShare folder # if not scratchWS: # Get the workspace of the output dataset (if any passed in) # by going up one level # if outDataset: scratchWS = os.path.dirname(str(outDataset)) # If this isn't a workspace, go up another level and # test again. # desc = arcpy.Describe(scratchWS) if desc.dataType.upper() <> "WORKSPACE": scratchWS = os.path.dirname(scratchWS) desc = arcpy.Describe(scratchWS) if desc.dataType.upper() <> "WORKSPACE": scratchWS = "" # If we have a workspace, make sure it's not a remote (SDE) database. # If it is remote, set workspace to the system temp directory. # # If we don't have a workspace, just set it to the system temp directory. # usingTemp = False if scratchWS: desc = arcpy.Describe(scratchWS) if desc.workspaceType.upper() == "REMOTEDATABASE": scratchWS = arcpy.GetSystemEnvironment("TEMP") usingTemp = True else: scratchWS = arcpy.GetSystemEnvironment("TEMP") usingTemp = True # If we're using the system temp directory (a shapefile workspace), look # for a scratch file geodatabase. If it exists, use it. If it doesn't, # create it. # if usingTemp: scratchWS = os.path.join(scratchWS, "scratch.gdb") if arcpy.Exists(scratchWS): return scratchWS else: arcpy.CreateFileGDB_management(arcpy.GetSystemEnvironment("TEMP"), "scratch.gdb") return scratchWS# Main demonstration routine# One optional input parameter, a feature class. #aDatasetpath = arcpy.GetParameterAsText(0)scratch = getScratchWorkspace(aDatasetpath)arcpy.AddMessage("Scratch workspace: " + scratch)# Create a scratch feature class in the scratch workspace#scrname = arcpy.CreateScratchName("temp", "","featureclass", scratch)arcpy.AddMessage("Scratch feature class is: " + scrname)arcpy.CreateFeatureclass_management(scratch, os.path.basename(scrname), "point")arcpy.AddMessage(arcpy.GetMessages())
Share Python Module
Similar to any modern programming language, Python allows you to call routines found in other Python scripts. With the development of Python code, you may want to develop Python routines that can be shared in scripts. This section briefly describes how to share routines and provides sufficient information so that you can effectively Study and Implement the sharing of routines from the official Python website (http://www.python.org.
The content of the script helloworld. py is as follows:
def dosomething(): print "Hello world"def somethingelse(): print "Goodbye world"
The content of Main. py is as follows:
import sys, os, helloworldhelloworld.dosomething()helloworld.somethingelse()
The main. py script imports the helloworld module (this module name is the script name with the. py extension removed) and the sys and OS modules. Note that the. py extension in helloworld is not required (in fact, it is not allowed ).
The helloworld. py script implements two routines called dosomething (using def statements). dosomething prints "Hello World" frequently, while somethingelse prints "Goodbye World" rarely ". When Main. py is executed, Main. py will call these two routines to print "Hello World" and "Goodbye World ".
The two modules shown above lack a lot of content, such as importing arcpy, obtaining the geographical processing environment, and error handling. InPython quick browsing covers all these topics.
Location of the python search Module
When Main. py is executed, the import command will make Python search for a file named helloworld. py in its system directory path list. Python will first search in the current directory, that is, the Directory of the script containing the import command (in this example, Main. py ). You can use the following code to display a list of these paths in the interactive pythonwin window:
import syssys.path
YouNoEnter the path in the import Command, as shown in figure
import E:\SharedScripts\helloworld
Instead, you must change the Directory List of the python search module. This directory list is included in the Windows environment settings named pythonpath and installed by ArcGIS. To change this setting, perform the following operations:
- Under the Windows Start Menu, click Settings> Control Panel.
- Find the system file and open it.
- Click the Advanced tab, and then click environment variables.
- Under the system variable, scroll to the pythonpath variable and click to select it.
- If the pythonpath variable does not exist, click New. In the variable name: text box, enter pythonpath.
- In the variable value: text box, enter <ArcGIS installation directory> \ bin; <ArcGIS installation directory \ arcpy (for example, c: \ Program Files \ ArcGIS \ toptop10.0 \ bin; C: \ Program Files \ ArcGIS \ topics top10.0 \ arcpy ).
- Click OK.
- If the pythonpath variable exists, click Edit.
The first entry in the pythonpath content should be <ArcGIS installation directory> \ bin; <ArcGIS installation directory \ arcpy. This is where the arcgisscripting module is located. You can append more paths to directories containing Python modules. These paths are separated by semicolons and there is no space between the left and right sides of the semicolon.
You can append the path to the Code in the following ways:
sys.path.append("e:\sharedmodules")
Share Python Module
To provide the script tool to other users and import the script to other modules, you can select either of the following methods:
- Store all scripts in the same directory.
- Notify the user to install other modules and modify the pythonpath variable somewhere in the system.
SYS. Path. append () is not recommended because it requires you to change the Python code.
Path and escape characters
The UNIX-based programming language and the C programming language are similar to Python. backslash (\) is considered as escape characters. For example, \ n is used to insert a carriage return when writing text output, while \ t is used to insert a tab. If the path in the script uses the backslash as the separator, Python searches for the delimiter and replaces it with the carriage return and tab characters when \ n and \ t are encountered. (Except \ n and \ t, there are other escape character sequences .)
The simplest way to prevent this situation is to use the R command to convert the path to the python original string, as shown below. This instructs python to ignore the backslash.
thePath = r"E:\data\teluride\newdata.gdb\slopes"
Learn more about setting data paths
Check license
If your scripts use extension modules or the required tools are unavailable at the ArcView or arceditor product level, you must first check the license and product level.
Learn more about the license check in the script
Quick browsing with related topic sharing tools