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]);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…