Python in ArcGIS – Access ArcGIS Python Environment from .bat Script

arcgis-onlinearcgis-python-apibatpython

I'm trying to run a Python script (shapefile_upload.py) which uses ArcGIS libraries. I installed the ArcGIS libraries by following exactly these instructions.

The Python script uploads a shapefile to ArcGIS Online. It takes several arguments (ArcGIS Online URL, path to shapefile, username, and password).

I need to run the Python script in a .bat file. The .bat file looks like this:

call "c:\ProgramData\Anaconda3\envs\ArcGIS_Test\python.exe" shapefile_upload.py URL Path_to_shapefile -U Username -P Password

When I select "Open Terminal" in Anaconda Navigator for the ArcGIS_Test environment and execute this .bat script, the shapefile is successfully uploaded to ArcGIS Online.

However, when I open a regular cmd window (not via Anaconda Navigator), and run the .bat script, I get an error that it's unable to ArcGIS Online, and the shapefile is not uploaded.

I think the Python environment is not used properly by the .bat file when run from the basic windows cmd window, even though I'm calling the Python interpreter within the correct environment.

What do I need to change in my .bat script for the environment to be set properly?

Best Answer

If you do not have ArcGIS Pro currently installed on your machine

If you installed the arcgis library through conda but do not have ArcGIS Pro installed on yout machine, you need to call the activate.bat file from the main conda folder and point it to your newly created environment.

Edit your .bat file to look like this:

@echo on

set env_name=ArcGIS_Test
set conda_dir=C:\ProgramData\Anaconda3
set env_dir=%conda_dir%\envs\%env_name%

call %conda_dir%\Scripts\activate.bat %env_dir%

%env_dir%\python.exe shapefile_upload.py URL Path_to_shapefile -U Username -P Password

pause

If you have ArcGIS Pro currently installed on your machine

According to this ArcGIS documentation, you need to refer to propy.bat instead of python.exe.

So have the contents of your .bat file to be as follows:

set arcgis_dir=C:\Program Files\ArcGIS\Pro
"%arcgis_dir%\bin\Python\scripts\propy.bat" shapefile_upload.py URL Path_to_shapefile -U Username -P Password

Small note

You might need to update the env_name, conda_dir and arcgis_dir variables to the actual paths and names used on your machine (i.e., the set xyz=abc statements at the top of the bash files).