vscode python remote interpreter

2020-07-10 07:55发布

问题:

By using VSCode (Visual Studio Code) I execute Python code on a local Python (Anaconda) interpreter. Now I would like to set it up so that I am able to execute that code on a remote Python interpreter. I have a Linux device which has its own Python and is accessible via ssh.
Is it possible to configure it? If so how? Thank you.

回答1:

While Microsoft is working on officially implementing this in VSCode (see: https://github.com/Microsoft/vscode-python/issues/79) I am personally using the following task defined in tasks.json for running Python on my remote machine. It contains two tasks: (1) synchronize the code to the remote machine using rsync; (2) execute the code over SSH in the remote interpreter. Note that the execution task dependsOn the sync task so that executing the code is always done from the latest local copy.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Synchronize Code",
            "type": "shell",
            "command": "rsync -axv --exclude-from=rsync-exclude.lst --max-size=5MB \"${workspaceFolder}\" user@hostname:dev/code-sync/",
            "problemMatcher": [],
            "isBackground": true,
            "presentation": {
                "echo": false,
                "reveal": "silent",
                "focus": false,
                "panel": "shared",
                "clear": false
            }
        },
        {
            "label": "Remote Execute",
            "type": "shell",
            "command": "ssh -n user@hostname \"source ~/.profile && source /path/to/virtualenv/bin/activate && python ~/dev/code-sync/${workspaceFolderBasename}/${relativeFile}\"",
            "dependsOn": [
                "Synchronize Code"
            ],
            "problemMatcher": []
        }
    ]
}

Note that you can also assign a keybinding to executing the task so that you can execute the Python code on the remote with a single keypress. Add to keybindings.json:

{
    "key": "cmd+shift+r",
    "command": "workbench.action.tasks.runTask",
    "args": "Remote Execute"
}