Question about using "diary" command

조회 수: 13 (최근 30일)
Bob
Bob 2025년 7월 7일
댓글: Bob 2025년 7월 8일
I'm trying to use the "diary()" command to capture the Command Window text to a log file. However, it's not behaving the way I expected. I don't know if I'm doing something wrong, or if I have an incorrect understanding of how "diary()" works.
Below is a toy program demonstrating how I'm using "diary()".
function diary_demo()
[~, host] = system('hostname');
host = host(~isspace(host));
user = getenv('USERNAME');
user = user(~isspace(user));
serial = now();
logfile = sprintf('%s-%s-%f.log', user, host, serial);
diary(logfile);
for i = 1:10
t = datetime('now');
fprintf('now = %s\n', string(t));
pause(1);
end
fprintf('Done!\n');
% With "diary('off')" commented-out, nothing is written to the log file
% until exiting MATLAB.
% With "diary('off')" active, Command Window text is written to the log
% file when the command runs, even if the m-file hasn't finished yet.
fprintf('About to pause 30 seconds before running "diary(''off'')".\n');
pause(30);
diary('off');
fprintf('"diary(''off'')" just ran. About to pause another 30 seconds before exiting the m-file.\n');
pause(30);
fprintf('Exiting m-file.\n');
What I expected was that lines written out to the Command Window (i.e. the datetime info) would be written to my log file at the same time.
What I got was that nothing was written to the log file until the "diary('off')" command ran. (Or until I exited MATLAB.) At that point, everything I had written to the Command Window was written to my log file in one lump.
Am I doing something wrong with the "diary()" command? Or do I have an incorrect understanding of how the "diary()" command works?

채택된 답변

Matt J
Matt J 2025년 7월 7일
편집: Matt J 2025년 7월 7일
I don't see anything about it in the documentation, but it makes sense that the file write would be postponed until after all text has been accumulated. Accumulating all of the text first makes it possible for diary() to anticipate the size of the file that is needed, and to allocate space.

추가 답변 (1개)

Steven Lord
Steven Lord 2025년 7월 7일
I'm not 100% sure of this, but perhaps the -logfile startup option would be of use to you. I think it might update the log file more frequently than diary updates the diary file.
  댓글 수: 1
Bob
Bob 2025년 7월 8일
Thanks!
I'll give the -logfile startup option a try but mainly for my own benefit / knowledge. Given the constraints I'm working under, I'm not sure it would work for me long-term. (Bit of a long story.)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by