Adding Python scripts to batch files
Scheduling your Python scripts to run at prescribed times will require that you create a batch file containing one or more scripts and/or operating system commands. These batch files can then be added to the Windows Scheduler to run at a specific time interval.
Getting ready
Batch files are text
files containing command-line sequences for running Python scripts or performing operating system commands. They have a file extension of .bat
, which Windows recognizes as an executable file. Since batch files simply contain command-line sequences, they can be written with any text editor, though it is recommended that you use a basic text editor such as Notepad, so that you can avoid the inclusion of invisible special characters, which are sometimes inserted by programs such as Microsoft Word. In this recipe, you will create a simple batch file that navigates to the directory containing your ListFields.py
script and executes it.
How to do it...
Follow these steps to create a batch file:
Open a notepad.
Add the following lines of text to the file:
cd c:\ArcpyBook\Appendix1 python ListFields.py c:\ArcpyBook\data Burglaries_2009.shp
Save the file to your desktop as
ListFields.bat
. Make sure you change the Save as Type drop-down list to All Files, or else you'll wind up with a file calledListFields.bat.txt
.In Windows, navigate to your desktop and double-click on
ListFields.bat
to execute the sequence of commands.A command prompt will be displayed during execution. After the commands have been executed, the command prompt will automatically close.
How it works...
Windows treats a batch file as an executable, so double-clicking on the file will automatically execute the sequence of commands contained within the file in a new command prompt window. All print
statements will be written to the window. After the commands have been executed, the command prompt will automatically close. In the event that you need to keep track of the output, you can write the statements to an output log file.
There's more...
Batch files can contain variables, loops, comments, and conditional logic. This functionality is beyond the scope of this recipe. However, if you'll be writing and running many scripts for your organization, it's worthwhile to spend some time learning more about batch files. Batch files have been around for a long time, so there is no shortage of information about these files on the Web. For more information about batch files, please consult the Wikipedia page for this topic.