Search code examples
pythonpython-3.xmatlabmatlab-engine

How to create a python 3 class to start MATLAB and keep it running?


I'm using matlab 2017b and python 3 on windows 10. I want to create a class that can start the matlab and keep it open. However, matlab closes right after I finished the python script. Here is the code:


import matlab.engine
class Test:
    def __init__(self):
        self.eng = matlab.engine.start_matlab("-desktop")

if __name__ == "__main__":
    Test()

I can open the matlab in python console with the "start_matlab" command, but with this class I will keep failing to keep it open. Anyone know how I could make this work?


Solution

  • That's expected. From the documentation:

    If you exit Python with an engine still running, then Python automatically stops the engine and its MATLAB process.

    It sounds to me like you just want to start MATLAB from Python, as opposed to actually using the MATLAB engine.

    To do so, you can use Python's subprocess standard library, e.g.:

    import subprocess
    
    class Test:
        def __init__(self):
            subprocess.run(r"C:\Program Files\MATLAB\R2020a\bin\matlab.exe")
    
    if __name__ == "__main__":
        Test()
    

    Now the script will launch MATLAB, and MATLAB will remain open on termination of the script. Obviously replace the path shown with the location of the MATLAB executable on your machine.