在MATLAB中,我们可以将以下内容放在一个名为的脚本中me.m.
delete('me.m');
Run Code Online (Sandbox Code Playgroud)
运行脚本后,它会自行删除.在MATLAB中这样安全吗?
Sue*_*ver 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')
Run Code Online (Sandbox Code Playgroud)
如果您再尝试再次运行此脚本,则无法找到该脚本.
关于存储在存储器中的功能,脚本等.您始终可以使用它clear来明确清除它们或从内存中清除特定类型的所有内容.
%// Clear out an explicit script
clear scriptname
%// Clear all functions & scripts
clear functions
Run Code Online (Sandbox Code Playgroud)
有趣的是,即使您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')
Run Code Online (Sandbox Code Playgroud)
另一个有趣的消息是,mlock它旨在防止当前正在执行的函数/脚本即使在完成后也从内存中删除.如果将其插入脚本(删除文件后),脚本在脚本完成后仍会显示,但是,由于找不到源文件,您仍然无法再次调用脚本.inmem
this = mfilename;
delete(which(this));
mlock
disp('Still here')
Run Code Online (Sandbox Code Playgroud)
然后从命令窗口
%// Run the self-destructing script
scriptname
%// Check to see if it is in memory
ismember('scriptname', inmem)
%// Now try to run it again (will not work)
scriptname
Run Code Online (Sandbox Code Playgroud)
从内部删除脚本是否安全?是的.看起来好像无法通过删除源文件来阻止当前正在执行的脚本运行完成.