1

I'm writing my first VSCode extension. In short, the extension opens a terminal (PowerShell) and executes a command:

term = vscode.window.activeTerminal;
term.sendText("ufs put C:\\\Users\\<userID>\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages\\mymodule.py");

After selecting a Python environment, VSCode should know where Python is located (python.pythonPath). But the path to Python will obviously vary depending on the Python installation, version and so on. So I was hoping that I could do something like:

term.sendText("ufs put python.pythonPath\\Lib\\site-packages\\mymodule.py");

But how can I do this in my extension (TypeScript)? How do I refer to python.pythonPath?

My configuration:

UPDATE:

Nathan, thank you for your comment. I used a child process as suggested. It executes a command to look for pip. Relying on the location of pip is not bullet proof, but it works for now:

var pwd = 'python.exe -m pip --version';
const cp = require('child_process');
cp.exec(pwd, (err, stdout, stderr) => {
    console.log('Stdout: ' + stdout);
    console.log('Stderr: ' + stderr);
    if (err) {
        console.log('error: ' + err);
    }
});

Not sure where to go from here to process stdout, but I tried child_process.spawn using this accepted answer:

function getPath(cmd, callback) {
    var spawn = require('child_process').spawn;
    var command = spawn(cmd);
    var result = '';
    command.stdout.on('data', function (data) {
        result += data.toString();
    });
    command.on('close', function (code) {
        return callback(result);
    });
}
let runCommand = vscode.commands.registerCommand('extension.getPath', function () {
    var resultString = getPath("python.exe -m pip --version", function (result) { console.log(result) });
    console.log(resultString);
});

Hopefully, this would give me stdout as a string. But the only thing I got was undefined. I'm way beyond my comfort zone now. Please advise me how to proceed.

oivron
  • 75
  • 4
  • As per [this question](https://stackoverflow.com/questions/43007267/how-to-run-a-system-command-from-vscode-extension) you have access to node.js libraries. You could use [child_process](https://nodejs.org/api/child_process.html) to run a command and capture stdout. You could run something like `python -c "import sys; print(sys.path)"` and process the output. On the other hand if `PYTHONPATH` is defined you could use the accepted answer in [this question](https://stackoverflow.com/questions/1489599/how-do-i-find-out-my-python-path-using-python) to print that. – Nathan Wride Mar 30 '20 at 06:50

0 Answers0