0

In my VS Code extension, I'd like to invoke a python file and append standard output to VSCode's output channel. I'm aware that I can create an output channel via vscode.window.createOutputChannel("..."); and I'm also aware I can execute such python (or for this matter, any local bash) script via these APIs: https://nodejs.org/api/child_process.html. Would it be possible to append standard out information to this output channel in real-time (i.e., as the script runs)?

What I currently have is the following:

export function execute(cmd: string, callback: any, logging?: vscode.OutputChannel) {
  const spwanedProcess = spawn(cmd, [], {shell: true, detached: true});
  console.log(`spawned pid ${spwanedProcess.pid} with command ${cmd}`);
  spwanedProcess.stdout.on('data', (data: any) => {
    console.log(data);
    logging?.appendLine("stdout:" + data);
  });
  spwanedProcess.stderr.on('data', (data: any) => {
    console.error(`spawned pid ${spwanedProcess.pid} pushed something to stderr`);
    logging?.appendLine(data);
  });

  spwanedProcess.on('exit', function(code: any) {
    if (code !== 0) {
      console.log('Failed: ' + code);
    }
    else {
      console.log(`pid ${spwanedProcess.pid} finished`);
    }
    callback();
  });
}

where callback() is something to be executed after the execution is done. I got this structure from here https://stackoverflow.com/a/32872753/14264786.

However, when I run a simple python code that sleeps for 3 seconds and prints something and does this again, the standard out information is still not displayed on the logging in real-time. Instead, they are outputted together after the script finishes.

Any idea on what's a potential solution?

Go_printf
  • 45
  • 4

1 Answers1

0

After some more digging, I found out that one solution is to use python -u to invoke the python script to unbuffer the python output

Go_printf
  • 45
  • 4