This post would be helpful for users of desktop GIS software such as ArcMap who need to use Python inside those applications.
There is a not so well known trick to trigger execution of a Python script before any Python interpreter on your system starts.
Note: If you are a QGIS user, there is a special way of achieving this. Please see the question Script that runs automatically from the QGIS Python Console when QGIS starts, using schedule tasks on Windows 10 for details.
The way to do this is to set up an environment variable called
PYTHONSTARTUP in your operating system. You need to do two things:
- Create an environment variable that would point to a path of a valid Python script file (
.py) with the code that you would like to get executed before any Python interactive interpreter starts. Look at the question [Installing pythonstartup file](https://stackoverflow.com/questions/5837259/installing-pythonstartup-file) for details.
- Write Python code that you would like to get executed.
A very important thing to consider is that
The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session.
This means that you can do a bunch of imports and define multiple variables which would be available to you directly at the start up of your GIS application. This is very handy because I often need to import the
sys modules as well as import
arcpy.mapping module and create
mxd variable pointing to the current map document I have open in ArcMap.
Here is the code of my startup Python script which you can modify to suit your needs. If your workflow relies on having some data at hand, then you might need to add more variables exposed. I have ArcMap and ArcGIS Pro users in mind.
I have included in the example above a more specific workflow where you would like to be able to quickly execute SQL queries against an enterprise geodatabase (SDE). So, when ArcMap has started, you only need to create a variable
conn pointing to a database connection file (
.sde) and then use the
sql() function running your query. Thanks to the
tabulate package, the list of lists you get back is drawn in a nice table format.