首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从GUI运行并终止外部.m-file

从GUI运行并终止外部.m-file
EN

Stack Overflow用户
提问于 2016-09-15 21:52:54
回答 1查看 208关注 0票数 2

我创建了一个小的MATLAB-GUI来选择一个目录,并通过单击一个按钮在这个目录中启动一个外部MATLAB脚本。脚本的路径保存在一个变量file中,我用run(file)启动它。但是现在我想通过单击另一个按钮来停止这个脚本。有谁知道怎么做吗?

EN

回答 1

Stack Overflow用户

发布于 2016-09-16 00:01:28

如果不想对要调用的脚本进行任何更改,可以尝试在新的Matlab实例中运行脚本,然后在想要停止脚本运行时终止该matlab进程。类似于:

代码语言:javascript
复制
oldPids = GetNewMatlabPIDs({}); % get a list of all the matlab.exe that are running before you start the new one
% start a new matlab to run the selected script
system('"C:\Program Files\MATLAB\R2012a\bin\matlab.exe" -nodisplay -nosplash -nodesktop -minimize -r "run(''PATH AND NAME OF SCRIPT'');exit;"');
pause(0.1); % give the matlab process time to start
newPids = GetNewMatlabPIDs(oldPids); % get the PID for the new Matlab that started
if length(newPids)==1
    disp(['new pid is: ' newPids{1}])    
elseif length(newPids)==0    
    error('No new matlab started, or it finished really quickly.');
else 
    error('More than one new matlab started.  Killing will be ambigious.');
end

pause(1);
% should check here that this pid is still running and is still 
% a matlab.exe process.
system(['Taskkill /PID ' newPids{1} ' /F']);

其中,GetNewMatlabPIDs从系统命令tasklist获取Matlab.exe的PID

代码语言:javascript
复制
function newPids = GetNewMatlabPIDs(oldPids)
tasklist = lower(evalc('system(''tasklist'')'));
matlabIndices = strfind(tasklist, 'matlab.exe');
newPids = {};
for matlabIndex = matlabIndices
    rightIndex = strfind(tasklist(matlabIndex:matlabIndex+100), 'console');
    subString = tasklist(matlabIndex:matlabIndex+rightIndex);
    pid = subString(subString>=48 & subString<=57);
    pidCellFind = strfind(oldPids, pid);
    pidCellIndex = find(not(cellfun('isempty', pidCellFind)));
    if isempty(pidCellIndex)
       newPids{end+1} = pid; 
    end
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39512890

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档