Search code examples
pythonmatlab

How to suppress matlab output from python


Suppose that you have the following .m script:

% foo.m
function foo = run()
    disp('Hello!!');
    foo = 1;
end

Now, you execute foo.m from python with:

import matlab.engine
eng = matlab.engine.start_matlab()
py_foo = eng.foo()

This code will set py_foo = 1 AND will display the output Hello. How do I suppress matlab output?


Solution

  • I answer my question.

    I didn't read carefully the matlab documentation about the Python API. Following the instruction at this page, the correct answer to my question is:

    import matlab.engine
    import io
    
    eng = matlab.engine.start_matlab(stdout=io.StringIO())
    py_foo = eng.foo()
    

    Out:

    // no output! :D
    

    Just in case you are using exec() (and be very sure about user inputs in this case), remember to import io inside the string passed to exec(), i.e.:

    import matlab.engine
    import io // this is useless!!
    
    eng = matlab.engine.start_matlab()
    str = "import io;eng.foo(stdout=io.stringIO())" // put it here
    loc = {}
    exec(str, {"eng" : eng}, loc)
    py_foo = loc["foo"]