列出Matlab中的所有环境变量 [英] List all environment variables in Matlab
问题描述
如何在Matlab中获取所有定义的环境变量的列表?我知道 getenv
,但您必须提供一个名称,而 doc getenv
不提供如何使用的帮助它以任何其他方式检索项目。我在网上找不到任何其他相关信息。这是甚么可能吗?
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?
我对平台无关的答案(或至少Windows和Linux)感兴趣。
I'm interested in a platform-independent answer (or at least Windows and Linux).
推荐答案
下面是一个实现两种方法来检索所有环境变量的函数(两种方法都是跨平台的):
Below is a function that implements two ways to retrieve all environment variables (both methods are cross-platform):
- 在MATLAB中使用Java功能
- 使用系统特定的命令(如 @sebastian 建议)
- using Java capabilities in MATLAB
- using system-specific commands (as @sebastian suggested)
注意:由于@Nzbuu在评论中解释,使用Java的 System.getenv()
有一个限制,它返回在MATLAB进程启动时捕获的环境变量。这意味着在当前会话中使用 setenv
进行的任何后续更改都不会反映在Java方法的输出中。基于系统的方法不会受此影响。
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.
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
示例:
% 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')
这篇关于列出Matlab中的所有环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!