Question about using "diary" command

9 次查看(过去 30 天)
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