VSCode API: Run a command in a terminal and use output

Viewed 2309

I'm currently building a VSCode extension that launches a shell command in a terminal. What I'd like to do is get the output as a string, but failing that I'd like to just display the output (or keep the terminal open).

I can get the terminal open and have it run using the following code:


let terminal = vscode.window.createTerminal({
    name: "My Command",
    cwd: cwd,
    hideFromUser: false,
    shellPath: script,
    shellArgs: args,
});
terminal.show()

This works great, the command runs and I can see the output in the terminal at the bottom, but it closes immediately when the command completes. Is there a way I can have the terminal remain open, or grab the command output somehow? I've been digging through the docs but there doesn't appear to be anything.

1 Answers

On Windows, using the link in the note above, and assuming you are essentially looking to run a powershell command or script and receive the output (rather than specifically use the terminal), this is an approach that works:

  import * as cp from "child_process";

  const execShell = (cmd: string) =>
    new Promise<string>((resolve, reject) => {
      cp.exec(cmd, (err, out) => {
        if (err) {
          return resolve(cmd+' error!');
          //or,  reject(err);
        }
        return resolve(out);
      });
    });

  //... show powershell output from 'pwd'...
  context.subscriptions.push(
    vscode.commands.registerCommand('test', async () => {
      const output = await execShell('powershell pwd');
      vscode.window.showInformationMessage(output);
    })
  );
Related