繁体   English   中英

什么是运行 python 文件的 VS 代码命令?

[英]What is a VS Code Command to run a python file?

我做了一个打开文件对话框的扩展。 我想做的是在选择文件后,我想要一个 python 文件运行。 我需要的是运行文件的 VS Code 命令(或者可能是 python 文件?)。

这是一个工作示例,其中我使用的命令是在当前活动编辑器中注释所选行的命令。 它工作得很好,所以我知道这个结构通常是正确的。 我只需要正确的命令来替换注释行命令。

下面是我上面提到的工作命令有问题的代码。 我使用这个资源找到了它: where I found the comment line command

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const { ChildProcess } = require('child_process');
const vscode = require('vscode');
const { execFile } = require('node:child_process');
const { stdout, stderr } = require('process');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

    
    let disposable = vscode.commands.registerCommand('fileDialog.openFile', function () {

        const options = {
            canSelectMany: false,
            openLabel: 'Open'
       };
        vscode.window.showOpenDialog(options).then(fileUri => {
            if (fileUri && fileUri[0]) {
                console.log('Selected file: ' + fileUri[0].fsPath);
                vscode.commands.executeCommand('python.execInInterminal');  
            }
        });
    });

    context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
    activate,
    deactivate
}

如果您只需要运行 Python 脚本,则可以 go 执行child_processspawn 如果您真的更喜欢依赖 Python 扩展,那么您至少需要将脚本的 Uri 输入到 executeCommand 的参数中——它是您找到的第二部分。

function activate(context) {

    let disposable = vscode.commands.registerCommand('fileDialog.openFile', function () {

        const options = {
            canSelectMany: false,
            openLabel: 'Open',
            filters: {
                'Python script': ['py']
            }
        };
        vscode.window.showOpenDialog(options).then((fileUris) => {
            // This will always get an array of Uris regardless of canSelectMany being false
            fileUris?.forEach(async (fileUri) => {
                console.log(`Selected file:  ${fileUri.fsPath}`);
                await vscode.commands.executeCommand('python.execInInterminal', fileUri.fsPath);
            });
        });
    });

    context.subscriptions.push(disposable);
}

如果你想处理更多的事情,你可以参考他们包含在 repo 中的 thenable unittest 代码: https://github.com/microsoft/vscode-python/blob/main/src/test/smoke/runInTerminal.smoke。 test.ts#L46-L48

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM