Neb
Neb

Reputation: 2280

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?

Upvotes: 2

Views: 1212

Answers (2)

allesgeklaut
allesgeklaut

Reputation: 16

For the sake of completeness, and for those who may come across this question, I wanted to leave the working solution here (working as of today, 2023-12-06). It is a combination of the answer by @Neb and the comment by @mkl.

What worked for me is the following code snippet:

import matlab.engine
import io
import os

eng = matlab.engine.start_matlab()
# optional: add a directory to the Matlab path
eng.addpath(eng.genpath(os.path.dirname(__file__)))
# Pass this stdout parameter, and eventually stderr, with every call
eng.foo(stdout=io.StringIO())

Upvotes: 0

Neb
Neb

Reputation: 2280

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"]

Upvotes: 2

Related Questions