I am calling a MATLAB program from a Python script using MathWorks's engine. The MATLAB program prints many lines, which I'd like to suppress. I tried the top two answers here, and they did not work. Here's a simple demo:
% test.m
function test()
fprintf('printing in MATLAB\n');
end
# test.py
from matlab import engine
import os
import sys
class suppressPrinting:
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._original_stdout
eng = engine.start_matlab()
with suppressPrinting():
print('printing in Python') # Will be suppressed correctly.
with suppressPrinting():
eng.test(nargout=0) # Will *not* be suppressed.
If you run test.py
, it will still print "printing in MATLAB". The statement "printing in Python" will be suppressed. Is there a way to suppress the MATLAB outputs?