在MATLAB中,我们可以将以下内容放在名为me.m
的脚本中。
delete('me.m');
运行脚本后,它会自行删除。在MATLAB中这样安全吗?
答案 0 :(得分:13)
脚本在您调用时由MATLAB编译,编译后的脚本加载到内存中,然后从内存运行。对于类,函数,脚本和MEX文件也是如此。您可以使用inmem
获取当前存储在内存中的所有源文件的列表。
如果从脚本中删除源文件,它仍将完成(因为它使用的是内存版本),但显然无法再次运行。
您可以通过将其粘贴在脚本中来自行查看
%// Prove that we started
disp('About to self destruct')
%// Get the name of the current script
this = mfilename;
%// Remove the source file
delete(which(this))
%// Make sure we actually removed it
if exist(which(this))
disp('Not deleted')
else
disp('File is gone!')
end
%// Check that it is still in memory
if any(ismember(this, inmem))
disp('Still in memory')
else
disp('Not found in memory')
end
%// Demonstrate that we still execute this
disp('I am unstoppable')
如果您再尝试再次运行此脚本,则无法找到它。
关于存储在内存中的函数,脚本等。您始终可以使用clear
明确清除它们或从内存中清除specific type的所有内容。
%// Clear out an explicit script
clear scriptname
%// Clear all functions & scripts
clear functions
有趣的是,即使您从脚本clear scriptname
中调用scriptname.m
,也不会阻止脚本完成。
%// Get the name of the script
this = mfilename;
%// Delete the file
delete(which(this));
%// Try to clear this script from memory
clear(this);
%// Prove that we're still running
disp('Still here')
另一个有趣的消息是mlock
旨在防止当前正在执行的函数/脚本即使在完成后也从内存中删除。如果您将其插入脚本中(删除文件后),脚本完成后,脚本仍然显示<{1}} ,但是,您仍然可以' t再次调用脚本,因为找不到源文件。
inmem
然后从命令窗口
this = mfilename;
delete(which(this));
mlock
disp('Still here')
从内部删除脚本是安全吗? 是即可。好像你无法通过删除源文件来阻止当前正在执行的脚本运行完成。