Instead of hardcoding your scripts with paths to specific datasets, you can make your scripts more flexible by allowing them to accept input in the form of parameters from the command prompt. These input parameters can be captured using Python's sys.argv[]
object.
Python's sys.argv[]
object allows you to capture input parameters from the command line when a script is executed. We will use an example to illustrate how this works. Take a look at the following screenshot:
Each word must be separated by a space. These words are stored in a zero-based list object called sys.argv[]
. In the sys.argv[]
object, the first item in the list referenced by the 0
index, stores the name of the script. In this case, it would be ListFields.py
. Each successive word is referenced by the next integer. Therefore, the first parameter (c:ArcpyBookdata
) will be stored in sys.argv[1]
, and the second parameter (Burglaries.shp
) will be stored in sys.argv[2]
. Each of the arguments in the sys.argv[]
object can be accessed and used inside your geoprocessing script. In this recipe, you're going to update the ListFields.py
script so that it accepts input parameters from the command line.
Follow these steps to create a Python script that can accept input parameters from the command prompt, using sys.argv[]
:
C:ArcpyBookAppendix1ListFields.py
in IDLE.sys
module:import arcpy import sys
wkspace = sys.argv[1]
fc = sys.argv[2]
ListFields()
function:arcpy.env.workspace = wkspace fields = arcpy.ListFields(fc)
Your completed script should appear as follows:
import arcpy import sys wkspace = sys.argv[1] fc = sys.argv[2] try: arcpy.env.workspace = wkspace fields = arcpy.ListFields(fc) for fld in fields: print(fld.name) except Exception as e: print(e.message)
C:ArcpyBookcodeAppendix1ListFields_Step2.py
solution file.C:ArcpyBookAppendix1
.python ListFields.py c:ArcpyBookdata Burglaries_2009.shp
Burglaries_2009.shp
file. The difference is that your script no longer has a hardcoded workspace and feature class name. You now have a more flexible script, which is capable of listing the attribute fields for any feature class.The sys
module contains a list object called argv[]
, which is used to store the input parameters for the command-line execution of a Python script. The first item stored in the list is always the name of the script. So, in this case, sys.argv[0]
contains ListFields.py
. Two parameters are passed into the script, including the workspace and a feature class. These are stored in sys.argv[1]
and sys.argv[2]
, respectively. These values are then assigned to variables and used in the script.