Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

batch file - matlab - display dos command output to static text

i am using GUI to call a terminal command. By using dos(my_command, '-echo') i can get the command output in Matlab's Command Window. Is there anyway to replicate that -echo in a static text in my GUI?

Currently, with my_command, I write the output to a log file, and update the static text's String by this log file after process finishes, but what I want is a live-view like in Command Window: output is displayed line by line in real-time. Thanks.

Update:

@Hoki: another question is: when the console commands are being executed, if I close the GUI then Matlab returns errors unstopable, how can I freeze the whole GUI until the commands are finished?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Matlab does not offer a native way to fetch results continuously during the execution of dos, unix and system. Nevertheless there is a possibility to achieve the desired behaviour.

This is the proposed work-around:

  • Execute your command and pipe the output to a file.
  • Use the & character to continue execution of the Matlab-code.
  • Read the contents of this file continuously and update the GUI accordingly.
  • Introduce a second temporary file indicating the end of the command to stop the update-process.

Here is the code:

% create figure and uicontrol
fh = figure;
txtbox = uicontrol(fh,'Style','edit','Max',30,'Min',0,...
                   'HorizontalAlignment','left',...
                   'FontName','FixedWidth',...
                   'Position',[30 30 450 200]);

% store current path
path = cd;

% delete token to make sure the loop continues as expected
warnstate = warning('off','MATLAB:DELETE:FileNotFound');
delete(fullfile(path,'temp_cmdlog_done'));
warning(warnstate); % restore original warning state

% execute dos-command in background
cmd = 'ping -c 5 192.168.200.1';
dos([cmd,' > temp_cmdlog && echo > temp_cmdlog_done &']);

% refresh text in uicontrol until dos-command is done
while 1
    out = fileread('temp_cmdlog');
    set(txtbox,'String',out);
    if exist(fullfile(path,'temp_cmdlog_done'),'file')
        break;
    end
    pause(0.2); % adjust to suit your needs
end

% delete the temporary files
delete(fullfile(path,'temp_cmdlog'));
delete(fullfile(path,'temp_cmdlog_done'));

% indicate that process finished
set(txtbox,'ForegroundColor',[0,0.5,0]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...