如何从 Visual Studio Code 中执行 Python 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29987840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:15:40  来源:igfitidea点击:

How to execute Python code from within Visual Studio Code

pythonvisual-studio-code

提问by RPiAwesomeness

Visual Studio Codewas recently released and I liked the look of it and the features it offered, so I figured I would give it a go.

Visual Studio Code最近发布,我喜欢它的外观和它提供的功能,所以我想我会试一试。

I downloaded the application from the downloads pagefired it up, messed around a bit with some of the features ... and then realized I had no idea how to actually execute any of my Python code!

我从下载页面下载了该应用程序 并启动了它,对某些功能进行了一些修改……然后意识到我不知道如何实际执行我的任何 Python 代码!

I really like the look and feel/usability/features of Visual Studio Code, but I can't seem to find out how to run my Python code, a real killer because that's what I program primarily in.

我真的很喜欢 Visual Studio Code 的外观和感觉/可用性/功能,但我似乎无法找到如何运行我的 Python 代码,这是一个真正的杀手,因为这是我编程的主要内容。

Does anyone know if there is a way to execute Python code in Visual Studio Code?

有谁知道是否有办法在 Visual Studio Code 中执行 Python 代码?

采纳答案by python_starter

Here is how to Configure Task Runner in Visual Studio Code to run a py file.

以下是如何在 Visual Studio Code 中配置 Task Runner 以运行 py 文件。

In your console press Ctrl+Shift+P(Windows) or Cmd+Shift+P(Apple) and this brings up a search box where you search for "Configure Task Runner" enter image description here

在您的控制台中按Ctrl+ Shift+ P(Windows) 或Cmd+ Shift+ P(Apple),这会出现一个搜索框,您可以在其中搜索“配置任务运行程序” 在此处输入图片说明

EDIT: If this is the first time you open the "Task: Configure Task Runner", you need to select "other" at the bottom of the next selection list.

编辑:如果这是您第一次打开“任务:配置任务运行器”,则需要在下一个选择列表底部选择“其他”。

This will bring up the properties which you can then change to suit your preference. In this case you want to change the following properties;

这将显示属性,然后您可以根据自己的喜好更改这些属性。在这种情况下,您要更改以下属性;

  1. Change the Command property from "tsc"(TypeScript) to "Python"
  2. Change showOutput from "silent"to "Always"
  3. Change args(Arguments) from ["Helloworld.ts"]to ["${file}"](filename)
  4. Delete the last property problemMatcher
  5. Save the changes made
  1. 将 Command 属性从"tsc"(TypeScript)更改为"Python"
  2. 将 showOutput 从更改"silent""Always"
  3. args(参数)从更改["Helloworld.ts"]["${file}"](文件名)
  4. 删除最后一个属性 problemMatcher
  5. 保存所做的更改

enter image description here

在此处输入图片说明

You can now open your py file and run it nicely with the shortcut Ctrl+Shift+B(Windows) or Cmd+Shift+B(Apple)

您现在可以打开您的 py 文件并使用快捷方式Ctrl+ Shift+ B(Windows) 或Cmd+ Shift+ B(Apple)很好地运行它

Enjoy!

享受!

回答by Fenton

You can add a custom taskto do this. Here is a basic custom task for Python.

您可以添加自定义任务来执行此操作。这是 Python 的基本自定义任务。

{
    "version": "0.1.0",
    "command": "c:\Python34\python",
    "args": ["app.py"],
    "problemMatcher": {
        "fileLocation": ["relative", "${workspaceRoot}"],
        "pattern": {
            "regexp": "^(.*)+s$",
            "message": 1
        }
    }
}

You add this to tasks.jsonand press CTRL+ SHIFT+ Bto run it.

您将其添加到tasks.json并按CTRL+ SHIFT+B运行它。

回答by Jun Han

There is a much easier way to run Python, no any configuration needed:

有一种更简单的方式来运行 Python,不需要任何配置:

  1. Install the Code Runner Extension.
  2. Open the Python code file in Text Editor.
  3. To run Python code:
    • use shortcut Ctrl+Alt+N
    • or press F1and then select/type Run Code,
    • or right click the Text Editor and then click Run Codein editor context menu
    • or click Run Codebutton in editor title menu
    • or click Run Codebutton in context menu of file explorer
  4. To stop the running code:
    • use shortcut Ctrl+Alt+M
    • or press F1and then select/type Stop Code Run
    • or right click the Output Channel and then click Stop Code Runin context menu
  1. 安装代码运行器扩展
  2. 在文本编辑器中打开 Python 代码文件。
  3. 要运行 Python 代码:
    • 使用快捷方式 Ctrl+Alt+N
    • 或按F1然后选择/键入Run Code,
    • 或右键单击文本编辑器,然后Run Code在编辑器上下文菜单中单击
    • 或单击Run Code编辑器标题菜单中的按钮
    • 或单击Run Code文件资源管理器上下文菜单中的按钮
  4. 停止正在运行的代码:
    • 使用快捷方式 Ctrl+Alt+M
    • 或按F1然后选择/键入Stop Code Run
    • 或右键单击输出通道,然后Stop Code Run在上下文菜单中单击

run python

运行蟒蛇

If you want to add Python path, you could Go to File->Preference->Settings, and add Python path like below:

如果要添加 Python 路径,可以转到File-> Preference-> Settings,然后添加 Python 路径,如下所示:

"code-runner.executorMap": 
{ 
  "python": "\"C:\Program Files\Python35\python.exe\" -u" 
}

In case you have installed Python extension and manually set your interpreter already, you could config your settings.json file as following:

如果您已经安装了 Python 扩展并手动设置了解释器,您可以按如下方式配置 settings.json 文件:

{
    "python.pythonPath": "C:\\python36\\python36.exe",
    "code-runner.executorMap": 
    { 
        "python": "$pythonPath -u $fullFileName" 
    }
}

回答by vlad2135

All these answers are obsolete now.

所有这些答案现在都过时了。

Currently you have to:

目前你必须:

  1. install Python language extension(and python, obviously)
  2. open folder (important!), open any python file inside that folder
  3. switch to debug "tab"(?) and click on the gearbox (with hint 'Configure of Fix 'launch.json'')
  4. save opened launch.json file (it's placed in .vscode subdir in the folder opened on step #2)
  5. finally, click green triangle or hit F5
  1. 安装Python 语言扩展(显然还有 Python)
  2. 打开文件夹(重要!),打开该文件夹内的任何python文件
  3. 切换到调试“选项卡”(?)并单击齿轮箱(带有提示“修复'launch.json'的配置”)
  4. 保存打开的 launch.json 文件(它被放置在第 2 步打开的文件夹中的 .vscode 子目录中)
  5. 最后,单击绿色三角形或按 F5

No additional extensions or manual launch.json editing is required now.

现在不需要额外的扩展或手动 launch.json 编辑。

回答by kenwarner

There is a Run Python File in Terminalcommand available in the Python for VS Codeextension.

Python for VS Code扩展中有一个Run Python File in Terminal命令可用。

Run Python File in Terminal

在终端中运行 Python 文件

回答by RMSD

To extend @vlad2135's answer(read his first); that is how you set up python debugging in VSCode with Don Jayamanne's great python extension(Which is a pretty full featured IDE for python these days, and arguably one of VS code's best language extensions IMO).

扩展@vlad2135 的回答(阅读他的第一个);这就是你如何在 VSCode 中使用 Don Jayamanne 的伟大 python扩展(这是一个功能非常齐全的 Python IDE,可以说是 VS Code 最好的语言扩展之一 IMO)设置 python 调试。

Basically when you click the gear icon, it creates a launch.json in your .vscodedirectory in your workspace. You can also make this yourself, but it's probably just simpler to let VSCode do the heavy lifting. Here's an example file:

基本上,当您单击齿轮图标时,它会.vscode在您工作区的目录中创建一个 launch.json 。你也可以自己做这个,但让 VSCode 做繁重的工作可能更简单。这是一个示例文件:

launch.json

launch.json

You'll notice something cool after you generate it. It automatically created a bunch of configurations(most of mine are cut off, just scroll to see them all) with different settings and extra features for different libraries or environments (like django). The one you'll probably end up using the most is python; which is a plain (in my case C)Python debugger, and easiest to work with settings wise. I'll make a short walkthrough of the json attributes for this one, since the others use the pretty much same configuration with only different interpreter paths and one or two different other features there.

生成后你会注意到一些很酷的东西。它自动为不同的库或环境(如 django)创建了一系列具有不同设置和额外功能的配置(我的大部分配置都被切断了,只需滚动即可查看所有配置)。你可能最终使用最多的是 python;这是一个普通的(在我的情况下是 C)Python 调试器,并且最容易使用设置。我将对这个 json 属性做一个简短的演练,因为其他人使用几乎相同的配置,只有不同的解释器路径和一两个不同的其他功能。

  • name: The name of the configuration. A useful example of why you would change it is if you have two python configurations which use the same type of config, but different arguments. It's what shows up in the box you see on the top left (my box says "python" since I'm using the default python config).
  • type: Interpreter type. You generally don't want to change this one.
  • request: How you want to run your code, and you generally don't want to change this one either. Default value is "launch", but changing it to "attach"allows the debugger to attach to an already running python process. Instead of changing it, add a configuration of type attach and use that.
  • stopOnEntry: Python debuggers like to have an invisible break-point when you start the program so you can see the entry-point file and where your first line of active code is. It drives some C#/Java programmers like me insane. falseif you don't want it, trueotherwise.
  • pythonPath: The path to your install of python. The default value gets the extension level default in the user/workspace settings. Change it here if you want to have different pythons for different debug processes. Change it in workspace settings if you want to change it for all debug processes set to the default config in a project. Change it in user setting to change where the extension finds python across all projects. (4/12/17 The following was fixed in extension version 0.6.1). Ironically enough, this gets auto-generated wrong. It auto-generates to "${config.python.pythonPath}" which is deprecated in the newer VSCode versions. It might still work, but you should use "${config:python.pythonPath}" instead for your default first python on your path or VS settings. (4/6/17 Edit: This should be fixed in the next release. The team commited the fix a few days ago.)
  • program: The initial file that you debugger starts up when you hit run. "${workspaceRoot}"is the root folder you opened up as your workspace (When you go over to the file icon, the base open folder.) Another neat trick if you want to get your program running quickly, or you have multiple entry points to your program is to set this to "${file}"which will start debugging at the file you have open and in focus in the moment you hit debug.
  • cwd: The current working directory folder of the project you're running. Usually you'll just want to leave this "${workspaceRoot}".
  • debugOptions: Some debugger flags. The ones in the picture are default flags, you can find more flags in the python debugger pages, I'm sure.
  • args: This isn't actually a default configuration setting, but a useful one nonetheless (and probably what the OP was asking about). These are the command line arguments that you pass in to your program. The debugger passes these in as though they you had typed: python file.py [args]into your terminal; passing each json string in the list to the program in order.
  • name:配置的名称。为什么要更改它的一个有用示例是,如果您有两个 python 配置,它们使用相同类型的配置,但参数不同。这就是您在左上角看到的框中显示的内容(我的框中显示“python”,因为我使用的是默认的 python 配置)。
  • 类型:解释器类型。你通常不想改变这个。
  • 请求:您希望如何运行您的代码,并且您通常也不想更改此代码。默认值为"launch",但将其更改为"attach"允许调试器附加到已运行的 python 进程。与其更改它,不如添加一个类型为 attach 的配置并使用它。
  • stopOnEntry:Python 调试器喜欢在您启动程序时设置一个不可见的断点,以便您可以看到入口点文件以及活动代码的第一行所在的位置。它让一些像我这样的 C#/Java 程序员发疯。false如果你不想要它,true否则。
  • pythonPath:安装python的路径。默认值获取用户/工作区设置中的扩展级别默认值。如果您想为不同的调试过程使用不同的 python,请在此处更改它。如果要为项目中设置为默认配置的所有调试进程更改它,请在工作区设置中更改它。在用户设置中更改它以更改扩展在所有项目中找到 python 的位置。(4/12/17 以下在扩展版本 0.6.1 中得到修复)。具有讽刺意味的是,这会自动生成错误。它会自动生成“${config.python.pythonPath}”,这在较新的 VSCode 版本中已被弃用。它可能仍然有效,但您应该使用“${config:python.pythonPath}”代替您的路径或 VS 设置中的默认第一个 python。(4/6/17 编辑:这应该在下一个版本中修复。团队几天前提交了修复。)
  • 程序:当您点击运行时,您调试器启动的初始文件。"${workspaceRoot}"是您作为工作区打开的根文件夹(当您转到文件图标时,基本打开文件夹。)如果您想让程序快速运行,或者您的程序有多个入口点,另一个巧妙的技巧是将此设置为"${file}"将在您打开并在您点击 debug 的那一刻聚焦的文件处开始调试
  • cwd:您正在运行的项目的当前工作目录文件夹。通常你只想离开 this "${workspaceRoot}"
  • debugOptions:一些调试器标志。图片中的那些是默认标志,您可以在python调试器页面中找到更多标志,我敢肯定。
  • args:这实际上不是默认配置设置,但仍然是一个有用的设置(并且可能是 OP 询问的内容)。这些是您传递给程序的命令行参数。调试器将这些传入,就像您在python file.py [args]终端中输入一样:将列表中的每个 json 字符串按顺序传递给程序。

You can go herefor more information on the VSCode file variables you can use to configure your debuggers and paths.

您可以在此处获取有关可用于配置调试器和路径的 VSCode 文件变量的更多信息。

You can go herefor the extension's own documentation on launch options, with both optional and required attributes.

您可以在此处获取有关启动选项的扩展自己的文档,包括可选属性和必需属性。

You can click the "Add Configuration" button at the bottom right if you don't see the config template already in the file. It'll give you a list to auto generate a configuration for most of the common debug processes out there.

如果您没有看到文件中已有的配置模板,您可以单击右下角的“添加配置”按钮。它将为您提供一个列表,用于为大多数常见调试过程自动生成配置。

Now, as per vlad's answer, you may add any breakpoints you need as per normal visual debuggers, choose which run configuration you want in the top left dropdown menu and you can tap the green arrow to the left to the configuration name to start your program.

现在,根据 vlad 的回答,您可以根据普通的可视化调试器添加您需要的任何断点,在左上角的下拉菜单中选择您想要的运行配置,然后点击配置名称左侧的绿色箭头以启动您的程序.

Pro tip:Different people on your team use different IDE's and they probably don't need your configurations files. VSCode nearly always puts it's IDE files in one place (by design for this purpose; I assume), launch or otherwise so make sure to add .vscode/to your .gitignore if this is your first time generating a VSCode file(This process will create the folder in your workspace if you don't have it already)!

专业提示:您团队中的不同人员使用不同的 IDE,他们可能不需要您的配置文件。VSCode 几乎总是将它的 IDE 文件放在一个地方(为此目的而设计;我假设),启动或以其他方式,因此.vscode/如果这是您第一次生成 VSCode 文件,请确保将其添加到您的 .gitignore(此过程将创建文件夹如果您还没有它,请在您的工作区中)!

回答by w1n5rx

A simple and direct Python extensionwould save both time and efforts. Linting, debugging, code completion are the available features once installation is done. After this, to run the code proper Python installation path needs to be configured in order to run the code. General settingsare available in Userscope and Workspacecan be configured for Python language– "python.pythonPath": "c:/python27/python.exe"With above steps at least the basic Python programs can be executed.

一个简单而直接的Python 扩展可以节省时间和精力。安装完成后,Linting、调试、代码完成是可用的功能。在此之后,要运行代码,需要配置正确的 Python 安装路径才能运行代码。通用设置用户范围内可用,工作区可以为 Python 语言配置——"python.pythonPath": "c:/python27/python.exe"通过上述步骤,至少可以执行基本的 Python 程序。

回答by NickD

You no longer need any additional extensions. You can simply switch the output of the debugger to the integrated terminal.

您不再需要任何额外的扩展。您可以简单地将调试器的输出切换到集成终端。

Ctrl+Shift+D, then select Integrated Terminal/Console from the dropdown at the top.

Ctrl+ Shift+ D,然后从顶部的下拉列表中选择集成终端/控制台。

回答by AndreaB

As stated in Visualstudio Code Documentation, just right-click anywhere in the editor and select Run Python File in Terminal.

Visualstudio 代码文档 中所述,只需右键单击编辑器中的任意位置并选择在终端中运行 Python 文件。

回答by Nikolay Kulachenko

So there're 4 ways to run Python in VSCode so far:

所以到目前为止,有 4 种方法可以在 VSCode 中运行 Python:

  1. Via an integrated terminal(c'mon it's integrated! So technically you run it from within the VSCode ;)
    • No need to install anyextension.
    • No need to create and configure anything(assuming that you already have pythonin your $PATH).
    • ?Space(open terminal) and python my_file.py(run file).
  2. Via custom Task(accepted @Fenton's answer):
    • No need to install anyextension.
    • Default VSCode's way of doing things.
    • Beware not to copy-paste the answerbecause its problemMatcher.pattern.regexpis broken and it hangs the editor. It's better to either delete problemMatcheror change the regexpto at least ^\\s+(.*)$.
  3. Via Code Runnerextension (@JanHan's answer):

    • Need to configure code-runner.executorMapin User Settings(add path to your python).
    • Very helpful extention especially if you run not only Python in VSCode.
  4. Via Microsoft's official Pythonextension (@vlad2135's answer):
    • Need to create launch.js(a couple of clicks in VSCode's Debug tab).
    • The extension is a must-have for those who wants to use VSCode as a primary IDE for Python.
  1. 通过集成终端(来吧,它是集成的!所以从技术上讲,您可以从 VSCode 中运行它;)
    • 无需安装任何扩展。
    • 无需创建和配置任何内容(假设python您的$PATH.
    • ?Space(打开终端)和python my_file.py(运行文件)。
  2. 通过自定义任务(接受@Fenton 的回答):
    • 无需安装任何扩展。
    • 默认 VSCode 的做事方式。
    • 请注意不要复制粘贴答案,因为它problemMatcher.pattern.regexp已损坏并且会挂起编辑器。最好删除problemMatcher或更改regexp为至少^\\s+(.*)$
  3. 通过Code Runner扩展(@JanHan 的回答):

    • 需要code-runner.executorMap用户设置中进行配置(将路径添加到您的python)。
    • 非常有用的扩展,特别是如果您不仅在 VSCode 中运行 Python。
  4. 通过微软官方的Python扩展(@vlad2135 的回答):
    • 需要创建launch.js(在 VSCode 的“调试”选项卡中单击几下)。
    • 对于那些想要使用 VSCode 作为 Python 主要 IDE 的人来说,该扩展是必备的。