Skip to content
safe_execute_external_command.m 1.06 KiB
Newer Older
function [ status, results ] = safe_execute_external_command( cmd )
%SAFE_EXECUTE_EXTERNAL_COMMAND Executes a command avoiding various Matlab pitfalls
%   Exectues the given command using the system function, while avoid
%   various pitfalls that occur while running the matlab context.
%   Specifically, it removes matlab related paths from the LB_LIBRARY_PATH.
%   It restores them on exit.

    old_path = getenv('LD_LIBRARY_PATH');
    new_path = old_path;
    
    new_path = regexp(new_path, ':', 'split');
    new_new_path = '';
    
    for i=1:size(new_path, 2)
        finds = strfind(lower(new_path(i)), 'matlab');
        if size(finds{1}) == [0 0]
            new_new_path = [new_new_path new_path{i} ':']; %#ok<AGROW> Since size is dynamically found
        end
    end
    
    setenv('LD_LIBRARY_PATH', new_new_path(1:size(new_new_path,2)-1))
    had_error = 0;
    try
        [ status, results ] = system( cmd );
    catch exception
        had_error = 1;
    end
    
    setenv('LD_LIBRARY_PATH', old_path);

    if had_error == 1
        throw(exception)
    end
end