How can I use multiple versions of Python in a single MATLAB session?

I have code which was developed using an older version of Python and I am unable to fully update my version of Python because the library I am using is not available in more recent versions. I would like to use newer versions of Python to ensure compatibility with recent versions of MATLAB while still using my old Python code for other parts of my code. I am wondering if it is possible to switch versions of Python within a MATLAB session so I can use this older library, but also use new versions and be able to work with future versions of MATLAB.
 
Are there any methods to switch versions of Python within a MATLAB session?

 Accepted Answer

There are three potential ways to use multiple versions of Python in a single MATLAB session:
 
1. By switching to “OutOfProcess” execution mode you can switch versions of Python without restarting MATLAB by using the “terminate” and “pyenv” commands as follows:
>> terminate(pyenv)
>> pyenv("Version", "3.9") % for example
The downside of this method is that the “terminate” command will remove any Python objects previously created with the older version, so this might not work depending on your code.
2. Setup the MATLAB Python environment for the newer version you wish to use and use the “subprocess” module in Python to run the older Python library. This method involves changing the Python implementation instead of changing versions in MATLAB.

More Answers (0)

Products

Release

R2023a

Community Treasure Hunt

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

Start Hunting!