Executing Python from MAXScript
Executing Python from MAXScript
You can execute Python commands and statements (can be a single command/expression
or a series of statements); or a Python script (for example, a .py script) from within MAXScript. Use the python.Execute and python.ExecuteFile commands respectively, as follows:
python.Execute "print 'hello'"
python.ExecuteFile "demoBentCylinder.py"
If you provide a full path using the ExecuteFile command; for example, as follows; 3ds Max looks for the Python file in the path provided.
python.ExecuteFile @"C:\Program Files\Autodesk\3ds Max 2015\scripts\Python\demoBentCylinder.py"
Otherwise, 3ds Max looks for the Python script under the following directories:
- User Scripts directory
- User Startup Scripts directory
- Scripts directory
- Startup Scripts
- Windows paths specified by the Path environment variable. To see a list of these directories, enter echo %path% in your command prompt.
For example, 3ds Max would search under the following directories: userscripts\python, userscripts\startup\python, scripts\python, scripts\startup\python, and subsequently the windows paths.
The output of the results from scripts are printed to the MAXScript Listener window.
NOTE: Python scripts run in MAXScript are not thread-safe. Python commands are always executed
in the main 3ds Max thread. You should not attempt to spawn separate threads in your
scripts (for example, by using the Python threading module).
Python interface methods
If you run
in MAXScript, you obtain, in the MAXScript Listener, a list of available methods.
The following list describes these methods and arguments:
- Init(): Loads Python if it is not loaded already.
- Execute() and ExecuteFile(): Loads Python if it is not loaded already. Use Init() if you know that you will be using Python, and do not want the delay associated with
loading it to occur the first time it is used. You would call python.Init() in a startup script to take the load time hit at startup, rather than while actually
using 3ds Max.
- throwOnError keyword argument: Controls whether MAXScript throws a runtime exception if an error
occurs while running a method. If set to true, you always obtain a return result code of #success because, in all other cases, a runtime exception would be thrown. It would be up
to the script writer to make the call within a try/catch in order to handle the exception.
-
GetLastError(): Returns, as a string, the error message associated with the last error encountered
while running the Init(), Execute(), or ExecuteFile() methods.
- Result codes (enums): When executing Python from MAXScript, the result codes can be the following constants:
- #success
- #pathError
- #initError
- #scriptFileError
- #executeError