List all environment variables in Matlab

与世无争的帅哥 提交于 2020-01-02 01:07:19

问题


How does one get a list of all defined environment variables in Matlab? I'm aware of getenv but you have to provide a name, and doc getenv offers no help in how to use it to retrieve items in any other way. I can't find any other relevant information online. Is this even possible?

I'm interested in a platform-independent answer (or at least Windows and Linux).


回答1:


Below is a function that implements two ways to retrieve all environment variables (both methods are cross-platform):

  1. using Java capabilities in MATLAB
  2. using system-specific commands (as @sebastian suggested)

NOTE: As @Nzbuu explained in the comments, using Java's System.getenv() has a limitation in that it returns environment variables captured at the moment the MATLAB process starts. This means that any later changes made with setenv in the current session will not be reflected in the output of the Java method. The system-based method does not suffer from this.

getenvall.m

function [keys,vals] = getenvall(method)
    if nargin < 1, method = 'system'; end
    method = validatestring(method, {'java', 'system'});

    switch method
        case 'java'
            map = java.lang.System.getenv();  % returns a Java map
            keys = cell(map.keySet.toArray());
            vals = cell(map.values.toArray());
        case 'system'
            if ispc()
                %cmd = 'set "';  %HACK for hidden variables
                cmd = 'set';
            else
                cmd = 'env';
            end
            [~,out] = system(cmd);
            vars = regexp(strtrim(out), '^(.*)=(.*)$', ...
                'tokens', 'lineanchors', 'dotexceptnewline');
            vars = vertcat(vars{:});
            keys = vars(:,1);
            vals = vars(:,2);
    end

    % Windows environment variables are case-insensitive
    if ispc()
        keys = upper(keys);
    end

    % sort alphabetically
    [keys,ord] = sort(keys);
    vals = vals(ord);
end

Example:

% retrieve all environment variables and print them
[keys,vals] = getenvall();
cellfun(@(k,v) fprintf('%s=%s\n',k,v), keys, vals);

% for convenience, we can build a MATLAB map or a table
m = containers.Map(keys, vals);
t = table(keys, vals);

% access some variable by name
disp(m('OS'))   % similar to getenv('OS')



回答2:


You could use

system('env')

on linux/mac, and

system('set') % hope I remember correctly, no windows at hand

In both cases you'd have to parse the output though, as it comes in the format variable=<variable-value>.



来源:https://stackoverflow.com/questions/20004955/list-all-environment-variables-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!