Question about using "diary" command

11 ビュー (過去 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 件のコメント
Bob
Bob 2025 年 7 月 8 日
Thanks!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeEntering Commands についてさらに検索

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by