3

In matlab I can change to another shell by the bang (!) Notation.

Example: I enter a conda Environment in MATLAB by the following command:

!cmd '"%windir%\System32\cmd.exe" /K ""C:\Program Files\Anaconda3\Scripts\activate_<conda-env-name>.bat" "C:\Program Files\Anaconda3""'

My MATLAB Command window then Displays following:

(<conda-env-name>) U:\some_starting_path>

Now, is there a way to send commands to this newly entered shell in a programmatic way, so that that command is evaluated in that very shell's syntax and not as a MATLAB-command? For example, how can I write code that will execute a Python command without needing to enter it manually into the command line?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Aliakbar Ahmadi
  • 366
  • 3
  • 14
  • 1
    Just for clarification: when you add `!` to any command window line, you are basically telling MATLAB to run whatever comes next in the *System command line*. So they are not valid MATLAB lines, they are valid OS lines. – Ander Biguri Dec 17 '19 at 15:22
  • 1
    [Call Python from MATLAB](https://www.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html) – Cris Luengo Dec 17 '19 at 15:23
  • [This](https://stackoverflow.com/q/27933270/2586922) may be useful – Luis Mendo Dec 17 '19 at 16:14

1 Answers1

1

Not using the ! command or system(). Those are "one and done" functions.

But you can use Java's java.lang.Process API from within Matlab to control and interact with an ongoing process.

function control_another_process

pb = java.lang.ProcessBuilder(["myCommand", "myArg1", "myArg2"]);
proc = pb.start;  % now proc is a java.lang.Process object
stdin = proc.getOutputStream;  % Here's how you send commands to the process
stdout = proc.getInputStream;  % And here's how you get its output
stderr = proc.getErrorStream;

% ... now do stuff with the process ...

end

You can use this with a shell, with python, or any other command.

Here's a Matlab class that wraps up the Java code to make it convenient to work with in Matlab: https://github.com/apjanke/janklab/blob/master/Mcode/classes/%2Bjl/%2Butil/Process.m

Andrew Janke
  • 23,508
  • 5
  • 56
  • 85