Optional usage of python in a Matlab script
3 views (last 30 days)
Show older comments
Hi all,
I wanted to use python optionally in a script. The Idea was to check for pyhton and if no compatible environment is found to skip this part.
Using a "if" to exclude the code part is not working if the user has no python installed.
It seems Matlab checks the script before running it and thn does not run it at all.
Also, when tyring to set a breakpoint:

At the current stage it is a very simple call used to publish data to a different system, which I wanted to be optional.
Using "eval" can be used to trick Maltab into running the script. (Not my prefered solution).
If I force the code to run the python command using eval, then even if no pyhton is installed, I end up with a quite clear execption:
identifier: 'MATLAB:Python:PythonUnavailable'
message: 'Python commands require a supported version of CPython. See Getting Started with Python.'
and the script continues to run as expected. It seems nothing terribly bad happens that in my opinion would "justifies" not running the script at all. I can check for pyenv, mask the code parts, and even if I run into it I still could handle the exception.
Is there a specific reason for this behavior?
Is there a more elegant way then eval to handle a optional py call?
The only other thing I can think of is to create a "mypy" wrapper function. (have not tried that yet)
Using Matlab2021b.
1 Comment
Stefan Kerber
on 16 Nov 2023
Hello Michael
I would expect that you could call
ee = pyenv;
installedPy = upper(ee.Executable);
at the beginning of your script. And then use
if contains(upper(env.Executable), "PYTHON")
CALL_TO_SOME_PYTHON_FUNCTION
end
to check if Python is installed on your system.
Does this help?
Best
Stefan
Answers (0)
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!