Getting Started: STK COM integration using Python

Information

 
QuestionHow do I use Python to drive STK?
Answer

Note:  You will need an STK Integration license to integrate Python with STK.

AGI recommends that you use Jupyter Notebook or IPython with an IDE such as Spyder (more similar to MATLAB), which can be downloaded for free with the Anaconda Python installer: https://www.anaconda.com/download/

After you have installed the distribution package, launch Jupyter Notebook or Spyder directly from the Windows start menu or from Anaconda Navigator.


1. Python with comtypes Library

Using the comtypes library will enable intellisense, but does require some casting.  To install the comtypes library, use the python package installer script (i.e. "pip install comtypes").
Type in the following code to connect to STK:
from win32api import GetSystemMetrics
import comtypes

# Start new instance of STK
from comtypes.client import CreateObject
uiApplication = CreateObject('STK11.Application')
uiApplication.Visible = True

# Alternatively, uncomment the following lines to get a reference to a running STK instance
# from comtypes.client import GetActiveObject
# uiApplication=GetActiveObject('STK11.Application')
# uiApplication.Visible=True

# Get our IAgStkObjectRoot interface
root=uiApplication.Personality2

#Note: When 'root=uiApplication.Personality2' is executed, the comtypes library automatically creates a gen folder that contains STKUtil and STK Objects. After running this at least once on your computer, the following two lines should be moved before the 'uiApplication=CreateObject("STK11.Application")' line for improved performance.  

from comtypes.gen import STKUtil
from comtypes.gen import STKObjects

NOTE: When upgrading to STK 12, you will have to clear the comtypes cache. Simply delete all of the files that are in this directory:

from comtypes.client import gen_dir
print(gen_dir)



2. Python with win32com Library

Alternatively, you can use standard Python with the win32com library, which will not have intellisense. To install the win32com library, use the python package installer script (i.e. "pip install win32com").

Type in the following code to connect to STK:
import win32com.client
# Start new instance of STK
uiApplication = win32com.client.Dispatch('STK11.Application')
uiApplication.Visible = True

# Alternatively, uncomment the following lines to get a reference to a running STK instance
# uiApplication = win32com.client.GetActiveObject('STK11.Application')

# Get our IAgStkObjectRoot interface
root = uiApplication.Personality2

3. AGI Python Resources

Resource File 2