How to configure Python environment for standalone applications created with MATLAB Compiler?

I have some MATLAB code that calls Python. I have compiled it into a standalone application with MATLAB Compiler. But when I deployed the app to my end client's machine, the app couldn't find Python. It reports the error:
Python commands require a supported version of CPython. See <a
href="matlab:helpview([docroot '/matlab/helptargets.map'],
'getting_started_python_interface')">Getting Started with Python</a>.
We have Python installed on the client's machine. How to set up Python for the standalone application?

 Accepted Answer

By default, the application will use the Python environment setting inherited from the MATLAB session that compiled it. So if the Python installation is different on the client machine, the app will fail to find Python and report the error "Python commands require a supported version of CPython."
To ensure that the Python environment is correctly configured no matter where it is installed on the client's machine, you can add a startup function to your application:
function startupFcn(app)
if isdeployed
% system command to find python executable
% Windows: where python - it will list all python
% executables on the path. The first one is the default
% version. If you want to use a different python version,
% configure your path environment variable.
% UNIX: which python
try
[~,cmdout]=system('where python')
pythonPath=extractBefore(cmdout,".exe");
pyenv('Version',[pythonPath '.exe']);
catch
% Your error handling here
warning('Failed to set up Python')
end
end
% print out pyenv to check and test with py.list
%% pyenv
%% demo=eval("py.list('demo')")
end
For UNIX systems, you can use the command "which python". You can also adjust the command to use a certain Python version for your application. For example, "which python2" to use Python 2:
[~,cmdout]=system('which python');
pyenv('Version',cmdout(1:end-1));
NOTE: If you are building an App Designer app and get the error:
Python is loaded. The environment cannot be changed while the interpreter is running.
To change the environment, call 'terminate(pyenv)' then call 'pyenv'.
after adding the above code to your app, wrap any py.* command in your app with the 'eval' function. This will prevent Python from being loaded unexpectedly. For example, instead of:
demo=py.list('demo');
you can use 'eval' as shown below:
demo=eval("py.list('demo')");

More Answers (0)

Products

Release

R2021b

Tags

No tags entered yet.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!