Matlab engine for python- redirect output to diary

5 views (last 30 days)
Hello, I'm running Matlab function using matlab engine (through python) and i want to redirect the function output into a file. My code:
eng = matlab.engine.start_matlab("-r")
eng.cd(sys.argv[1])
funcName = sys.argv[2]
eng.eval("clc; diary out.txt; " + funcName + "; diary off;")
eng.quit()
The function is running and the file out.txt created however the output is not written to it. Can someone help me solve this problem. Thanks!
  2 Comments
Arthur
Arthur on 24 Nov 2017
Same problem here.
Tried with this non-ascii diary workaround (from here) but this would unfortunately leave 'txt' var empty when called under python matlab engine.
% Output Command Window text to a text file
function saveCmdWinText(filename)
cmdWinDoc = com.mathworks.mde.cmdwin.CmdWinDocument.getInstance;
txt = char(cmdWinDoc.getText(0,cmdWinDoc.getLength));
fid = fopen(filename,'W');
fwrite(fid,txt,'uint16'); % store as 2-byte characters
fclose(fid);
%winopen(filename); % in case you wish to verify...
end

Sign in to comment.

Answers (1)

Alan Frankel
Alan Frankel on 18 Jul 2025
Rather than an eval command:
>>> eng.eval("diary out.txt")
execute the MATLAB "diary" function directly from the engine handle:
>>> eng.diary("out.txt", nargout=0)
When I do this, I find that the output is captured in the diary file.

Community Treasure Hunt

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

Start Hunting!