Skip to content

Commit 3b232a5

Browse files
committed
subprocess_run: env= uses R2022b+ syntax for robustness
1 parent e635358 commit 3b232a5

File tree

2 files changed

+17
-16
lines changed

2 files changed

+17
-16
lines changed

+stdlib/+sys/subprocess_run.m

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
arguments
2323
cmd_array (1,:) string
24-
opt.env (1,1) struct = struct()
24+
opt.env struct {mustBeScalarOrEmpty} = struct.empty
2525
opt.cwd string {mustBeScalarOrEmpty} = string.empty
2626
end
2727

@@ -33,23 +33,25 @@
3333
cmd = exe;
3434
end
3535

36-
for f = string(fieldnames(opt.env)).'
37-
if ispc
38-
cmd = append("set ", f, "=", opt.env.(f), " && ", cmd);
39-
else
40-
cmd = append(f, "=", opt.env.(f), " ", cmd);
41-
end
42-
end
43-
4436
if ~isempty(opt.cwd)
4537
cwd = stdlib.fileio.absolute_path(opt.cwd);
4638
assert(isfolder(cwd), "subprocess_run: %s is not a folder", cwd)
4739
oldcwd = pwd;
4840
cd(cwd)
4941
end
5042

51-
[status, msg] = system(cmd);
43+
old = verLessThan('matlab', '9.13');
44+
if old && ~isempty(opt.env)
45+
warning("Matlab >= R2022b required for 'env' option of subprocess_run()")
46+
end
47+
48+
if isempty(opt.env) || old
49+
[status, msg] = system(cmd);
50+
else
51+
envCell = namedargs2cell(opt.env);
5252

53+
[status, msg] = system(cmd, envCell{:});
54+
end
5355
if ~isempty(opt.cwd)
5456
cd(oldcwd)
5557
end

+stdlib/+test/TestSys.m

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,17 @@
44

55
function test_simple_run(tc)
66

7-
import stdlib.sys.subprocess_run
8-
97
if ispc
108
c = 'dir';
119
else
1210
c = 'ls';
1311
end
14-
tc.verifyEqual(subprocess_run(c), 0)
12+
tc.verifyEqual(stdlib.sys.subprocess_run(c), 0)
1513
end
1614

1715

1816
function test_env_run(tc)
19-
20-
import stdlib.sys.subprocess_run
17+
tc.assumeFalse(verLessThan('matlab', '9.13'), "system(..., EnvName=, EnvVal=) requires Matlab R2022b+")
2118

2219
names = ["TEST1", "TEST2"];
2320
vals = ["test123", "test321"];
@@ -26,12 +23,14 @@ function test_env_run(tc)
2623

2724
% NOTE: test function cannot get specific variables without invoking a
2825
% subshell, as echo is evaluated in current shell before &&
26+
% Thus we just print the entire environment
2927
if ispc
3028
c = "set";
3129
else
3230
c = "env";
3331
end
34-
[ret, msg] = subprocess_run(c, "env", env);
32+
33+
[ret, msg] = stdlib.sys.subprocess_run(c, env=env);
3534
tc.verifyEqual(ret, 0)
3635
tc.verifyTrue(contains(msg, names(1) + "=" + vals(1)) && contains(msg, names(2) + "=" + vals(2)))
3736

0 commit comments

Comments
 (0)