Opening Anaconda Command Prompt in Matlab

7 views (last 30 days)
Matlab12345
Matlab12345 on 3 Aug 2023
Answered: Arjun on 23 Aug 2024
I want to write a Matlab script that can open a command prompt from another program and then pass input to it. As an example, I want to use Process.StartInfo.Filename to specify the location of the Anaconda command prompt. This is the location of the command prompt on my computer:
%windir%\System32\cmd.exe "/K" C:\Users\User\AppData\Local\anaconda3\Scripts\activate.bat C:\Users\User\AppData\Local\anaconda3
However, I get an error if I use Process.StartInfo.Filename with it:
Process.StartInfo.FileName = "%windir%\System32\cmd.exe "/K" C:\Users\User\AppData\Local\anaconda3\Scripts\activate.bat C:\Users\User\AppData\Local\anaconda3";
Invalid use of operator.
The issue seems to be the /k switch. How would I correctly specify this type of file name?

Answers (1)

Arjun
Arjun on 23 Aug 2024
Hi,
As per my understanding, you are encountering an error ‘invalid use of operator’ while opening Anaconda Command Prompt from MATLAB Script.
Kindly refer to the code below to open the Anaconda command Prompt:
% Create a .NET Process object
% This object allows you to start and control system processes from MATLAB.
process = System.Diagnostics.Process();
% Set the FileName to the command prompt executable
% This will retrieve windows directory path and construct full path to cmd
process.StartInfo.FileName = fullfile(getenv('windir'), 'System32', 'cmd.exe');
% Set the arguments to include the /K switch and the Anaconda activation script
% /K is a command-line switch for cmd.exe that tells the command prompt to execute the specified command and then remain open.
process.StartInfo.Arguments = sprintf('/K "C:\\Users\\User\\AppData\\Local\\anaconda3\\Scripts\\activate.bat C:\\Users\\User\\AppData\\Local\\anaconda3"');
% Set UseShellExecute to false to allow input/output redirection which is necessary for interacting with the command prompt programmatically.
process.StartInfo.UseShellExecute = false;
% Set RedirectStandardInput to true to allow input to be passed to the command prompt
% This enables the process to accept input from MATLAB, allowing you to send commands to the command prompt after it starts.
process.StartInfo.RedirectStandardInput = true;
% Start the processwith the specified executable and arguments. It opens a command prompt that executes the Anaconda activation script.
process.Start();
I hope it will help!

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!