简体   繁体   English

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

[英]How to execute Python code from within Visual Studio Code

Visual Studio Code was 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 page , fired 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 代码,这是一个真正的杀手,因为这是我编程的主要内容。

Is there is a way to execute Python code in Visual Studio Code?有没有办法在 Visual Studio Code 中执行 Python 代码?

There is a much easier way to run Python, and it doesn't need any configuration:有一种更简单的方式来运行 Python,它不需要任何配置:

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

运行 Python

If you want to add the Python path, you could go to FilePreferenceSettings , and add the Python path like below:如果要添加 Python 路径,可以转到FilePreferenceSettings ,然后添加 Python 路径,如下所示:

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

In case you have installed the Python extension and manually set your interpreter already, you could configure your settings.json file as follows:如果您已经安装了 Python 扩展并手动设置了解释器,您可以按如下方式配置您的settings.json文件:

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

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).在您的控制台中,按Ctrl + Shift + P (Windows) 或Cmd + Shift + P (Apple)。 This brings up a search box where you search for "Configure Task Runner"这会打开一个搜索框,您可以在其中搜索“配置任务运行器”

在此处输入图像描述

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

在此处输入图像描述

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) 很好地运行它。

All these answers are obsolete now.所有这些答案现在都已过时。

Currently you have to:目前,您必须:

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

No additional extensions or manual launch.json editing is required now.现在不需要额外的扩展或手动launch.json编辑。

You can add a custom task to 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 file tasks.json and press Ctrl + Shift + B to run it.您将其添加到文件tasks.json并按Ctrl + Shift + B运行它。

To extend vlad2135's answer (read his first);扩展vlad2135 的答案(先阅读他的); that is how you set up Python debugging in Visual Studio Code with Don Jayamanne's great Python extension (which is a pretty full featured IDE for Python these days, and arguably one of Visual Studio Code's best language extensions, IMO).这就是您在 Visual Studio Code 中使用Don Jayamanne 出色的 Python 扩展(它是当今 Python 的功能非常齐全的 IDE,可以说是 Visual Studio Code 的最佳语言扩展之一,IMO 之一)在 Visual Studio Code 中设置 Python 调试的方式。

Basically, when you click the gear icon, it creates a launch.json file in your .vscode directory in your workspace.基本上,当您单击齿轮图标时,它会在您工作区的.vscode目录中创建一个launch.json文件。 You can also make this yourself, but it's probably just simpler to let Visual Studio Code do the heavy lifting.您也可以自己制作,但让 Visual Studio Code 完成繁重的工作可能更简单。 Here's an example file:这是一个示例文件:

文件启动.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).它自动为不同的库或环境(如 Django)创建了具有不同设置和额外功能的一堆配置(我的大部分都被切断了;只需滚动查看它们)。

The one you'll probably end up using the most is Python;您最终可能会使用最多的是 Python。 which is a plain (in my case C)Python debugger and is easiest to work with settings wise.这是一个简单的(在我的情况下是 C)Python 调试器,并且最容易使用设置。

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.我将为这个 JSON 属性做一个简短的演练,因为其他的使用几乎相同的配置,只有不同的解释器路径和一两个不同的其他特性。

  • name: The name of the configuration. name:配置的名称。 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.为什么要更改它的一个有用示例是,如果您有两个 Python 配置,它们使用相同类型的配置,但参数不同。 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 configuration).这就是您在左上角看到的框中显示的内容(我的框显示为“python”,因为我使用的是默认 Python 配置)。
  • 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. request:你想如何运行你的代码,你通常也不想改变这个。 Default value is "launch" , but changing it to "attach" allows the debugger to attach to an already running Python process.默认值为"launch" ,但将其更改为"attach"允许调试器附加到已经运行的 Python 进程。 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. stopOnEntry:Python 调试器喜欢在您启动程序时设置一个不可见的断点,以便您可以看到入口点文件以及第一行活动代码的位置。 It drives some C#/Java programmers like me insane.它让一些像我这样的 C#/Java 程序员发疯。 false if you don't want it, true otherwise.如果您不想要它,则为false ,否则为true
  • pythonPath: The path to your install of Python. pythonPath:安装 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.如果您想为不同的调试过程使用不同的 Python,请在此处更改。 Change it in workspace settings if you want to change it for all debug processes set to the default configuration in a project.如果要为项目中设置为默认配置的所有调试进程更改它,请在工作区设置中更改它。 Change it in user setting to change where the extension finds Pythons across all projects.在用户设置中更改它以更改扩展在所有项目中找到 Python 的位置。 (4/12/2017 The following was fixed in extension version 0.6.1). (4/12/2017 以下已在扩展版本 0.6.1 中修复)。 Ironically enough, this gets auto-generated wrong.具有讽刺意味的是,这会自动生成错误。 It auto-generates to "${config.python.pythonPath}" which is deprecated in the newer Visual Studio Code versions.它会自动生成“${config.python.pythonPath}”,在较新的 Visual Studio Code 版本中已弃用。 It might still work, but you should use "${config:python.pythonPath}" instead for your default first python on your path or Visual Studio Code settings.它可能仍然有效,但您应该使用 "${config:python.pythonPath}" 代替路径上的默认第一个 python 或 Visual Studio Code 设置。 (4/6/2017 Edit: This should be fixed in the next release. The team committed the fix a few days ago.) (4/6/2017 编辑:这应该在下一个版本中修复。团队几天前提交了修复。)
  • 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). "${workspaceRoot}"是您作为工作区打开的根文件夹(当您转到文件图标时,基本打开文件夹)。 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 .如果你想让你的程序快速运行,或者你的程序有多个入口点,另一个巧妙的技巧是将它设置为"${file}" ,它将在你打开的文件开始调试,并在你关注的那一刻开始点击调试
  • cwd: The current working directory folder of the project you're running. cwd:您正在运行的项目的当前工作目录文件夹。 Usually you'll just want to leave this "${workspaceRoot}" .通常你只想离开这个"${workspaceRoot}"
  • debugOptions: Some debugger flags. debugOptions:一些调试器标志。 The ones in the picture are default flags, you can find more flags in the python debugger pages, I'm sure.图片中的那些是默认标志,我敢肯定,您可以在 python 调试器页面中找到更多标志。
  • args: This isn't actually a default configuration setting, but a useful one nonetheless (and probably what the OP was asking about). args:这实际上不是默认配置设置,但仍然是一个有用的设置(可能是 OP 所要求的)。 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;调试器将它们传递进来,就像你输入的一样: python file.py [args]到你的终端; passing each JSON string in the list to the program in order.按顺序将列表中的每个 JSON 字符串传递给程序。

You can go here for more information on the Visual Studio Code file variables you can use to configure your debuggers and paths.您可以在此处获取有关可用于配置调试器和路径的 Visual Studio Code 文件变量的更多信息。

You can go here for 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 IDEs and they probably don't need your configuration files.专业提示:您团队中的不同人员使用不同的 IDE,他们可能不需要您的配置文件。 Visual Studio Code 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 directory .vscode/ to your .gitignore if this is your first time generating a Visual Studio Code file (this process will create the folder in your workspace if you don't have it already)! Visual Studio Code 几乎总是将它的 IDE 文件放在一个地方(为此目的而设计;我假设)、启动或其他方式,如果这是您第一次生成 Visual Studio Code,请确保将目录.vscode/添加到您的 .gitignore文件(如果您还没有该文件夹,此过程将在您的工作区中创建该文件夹)!

There is a Run Python File in Terminal command available in the Python for Visual Studio Code extension.Python for Visual Studio Code扩展中有一个Run Python File in Terminal命令可用。

在终端中运行 Python 文件

Visual Studio Code 文档中所述,只需右键单击编辑器中的任意位置,然后选择在终端中运行 Python 文件

So there are four ways to run Python in Visual Studio Code so far:所以到目前为止,在 Visual Studio Code 中运行 Python 的方法有四种:

  1. Via an integrated terminal (come on, it's integrated ! So technically you run it from within Visual Studio Code ;)通过 集成终端(来吧,它是集成的!所以从技术上讲,您可以从 Visual Studio Code 中运行它;)
  • No need to install any extension.无需安装任何扩展。
  • No need to create and configure anything (assuming that you already have python in your $PATH ).无需创建和配置任何东西(假设您的$PATH中已经有python )。
  • ⌃Space (open terminal) and python my_file.py (run file). ⌃Space (打开终端)和python my_file.py (运行文件)。
  1. Via custom Task (accepted Fenton's answer ):通过自定义任务(接受Fenton 的回答):
  • No need to install any extension.无需安装任何扩展。
  • Default Visual Studio Code's way of doing things.默认 Visual Studio Code 的处理方式。
  • Beware not to copy-paste the answer because its problemMatcher.pattern.regexp is broken and it hangs the editor.请注意不要复制粘贴答案,因为它的problemMatcher.pattern.regexp已损坏并且会挂起编辑器。 It's better to either delete problemMatcher or change the regexp to at least ^\\s+(.*)$ .最好删除problemMatcher或将正则regexp更改为至少^\\s+(.*)$
  1. Via Code Runner extension (@JanHan's answer):通过Code Runner扩展(@JanHan 的回答):
  • Need to configure code-runner.executorMap in User Settings (add path to your python ).需要在用户设置中配置code-runner.executorMap (添加路径到你的python )。
  • Very helpful extension especially if you run not only Python in Visual Studio Code.非常有用的扩展,特别是如果您不仅在 Visual Studio Code 中运行 Python。
  1. Via Microsoft's official Python extension ( vlad2135's answer ):通过微软的官方 Python 扩展vlad2135 的回答):
  • Need to create launch.js (a couple of clicks in Visual Studio Code's Debug tab).需要创建launch.js (在 Visual Studio Code 的 Debug 选项卡中单击几下)。
  • The extension is a must-have for those who wants to use Visual Studio Code as a primary IDE for Python.对于想要将 Visual Studio Code 用作 Python 的主要 IDE 的人来说,该扩展是必不可少的。
  1. Install the Python extension (Python should be installed in your system).安装 Python 扩展(Python 应该安装在您的系统中)。 To install the Python Extension, press Ctrl + Shift + X and then type 'python' and enter.要安装 Python 扩展,请按Ctrl + Shift + X ,然后键入“python”并回车。 Install the extension.安装扩展。

  2. Open the file containing Python code.打开包含 Python 代码的文件。 Yes!是的! A .py file.一个 .py 文件。

  3. Now to run the .py code, simply right click on the editor screen and hit 'Run Python File in the Terminal'.现在要运行 .py 代码,只需右键单击编辑器屏幕并点击“在终端中运行 Python 文件”。 That's it!而已!

Now this is the additional step.现在这是附加步骤。 Actually I got irritated by clicking again and again, so I set up the keyboard shortcut.实际上,我一次又一次地点击感到恼火,所以我设置了键盘快捷键。

  1. Hit that Settings-type-looking-like icon on bottom-left side → Keyboard Shortcuts → type 'Run Python File in the Terminal'.点击左下角的类似设置类型的图标→键盘快捷键→键入“在终端中运行 Python 文件”。 Now you will see that + sign, go choose your shortcut.现在你会看到那个+号,去选择你的快捷方式。 You're done !完成了

There is a lot of confusion around Visual Studio Code tasks and the debugger. Visual Studio Code 任务和调试器存在很多混淆。 Let's discuss about it first so that we understand when to use tasks and when to use the debugger.让我们先讨论一下,以便我们了解何时使用任务以及何时使用调试器。

Tasks任务

The official documentation says -官方文档说 -

Lots of tools exist to automate tasks like linting, building, packaging, testing, or deploying software systems.有很多工具可以自动执行检查、构建、打包、测试或部署软件系统等任务。 Examples include the TypeScript Compiler, linters like ESLint and TSLint as well as build systems like Make, Ant, Gulp, Jake, Rake, and MSBuild.示例包括 TypeScript 编译器、像 ESLint 和 TSLint 这样的 linter,以及像 Make、Ant、Gulp、Jake、Rake 和 MSBuild 这样的构建系统。

.... Tasks in VS Code can be configured to run scripts and start processes so that many of these existing tools can be used from within VS Code without having to enter a command line or write new code. .... VS Code 中的任务可以配置为运行脚本和启动进程,这样许多现有工具就可以在 VS Code 中使用,而无需输入命令行或编写新代码。

So, tasks are not for debugging, compiling or executing our programs.因此,任务不是用于调试、编译或执行我们的程序。

Debugger调试器

If we check the debugger documentation, we will find there is something called run mode .如果我们检查调试器文档,我们会发现有一个叫做 运行模式的东西。 It says -它说 -

In addition to debugging a program, VS Code supports running the program.除了调试程序,VS Code 还支持运行程序。 The Debug: Start Without Debugging action is triggered with Ctrl+F5 and uses the currently selected launch configuration. Debug: Start without Debugging操作由Ctrl+F5触发并使用当前选择的启动配置。 Many of the launch configuration attributes are supported in 'Run' mode. “运行”模式支持许多启动配置属性。 VS Code maintains a debug session while the program is running, and pressing the Stop button terminates the program. VS Code 在程序运行时维护一个调试会话,按下停止按钮会终止程序。

So, press F5 and Visual Studio Code will try to debug your currently active file.因此,按F5 ,Visual Studio Code 将尝试调试您当前活动的文件。

Press Ctrl + F5 and Visual Studio Code will ignore your breakpoints and run the code.Ctrl + F5和 Visual Studio Code 将忽略您的断点并运行代码。

Configuring the debugger配置调试器

To configure the debugger, go through the documentation .要配置调试器,请阅读文档 In summary it says, you should modify the launch.json file.总之,它说,您应该修改launch.json文件。 For starters, to run the code in integrated terminal (inside Visual Studio Code), use -对于初学者,要在集成终端(在 Visual Studio Code 中)运行代码,请使用 -

{
    "name": "Python: Current File (Integrated Terminal)",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal"
}

To run the code in an external terminal (outside of Visual Studio Code), use -要在外部终端(Visual Studio Code 之外)中运行代码,请使用 -

{
    "name": "Python: Current File (External Terminal)",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "externalTerminal"
}

NB If all documentation was easy to search and understand then we probably would not need Stack Overflow.注意如果所有文档都易于搜索和理解,那么我们可能不需要 Stack Overflow。 Fortunately, the documentation I mentioned in this post is really easy to understand.幸运的是,我在这篇文章中提到的文档非常容易理解。 Please feel free to read, ponder and enjoy.请随意阅读、思考和享受。

In the latest version (1.36) of Visual Studio Code (Python):在 Visual Studio Code (Python) 的最新版本 (1.36) 中:

Press F5 and then hit Enter to run your code in the integrated terminal.F5然后按Enter在集成终端中运行您的代码。

Ctrl + A and then hit Shift + Enter to run your code in the interactive IPython shell. Ctrl + A然后按Shift + Enter在交互式IPython shell 中运行您的代码。

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 ,然后从顶部的下拉列表中选择集成终端/控制台。

Here's the current (September 2018) extensions for running Python code:这是运行 Python 代码的当前(2018 年 9 月)扩展:

Official Python extension : This is a must install. 官方 Python 扩展:这是必须安装的。

Code Runner : Incredibly useful for all sorts of languages, not just Python. Code Runner :对各种语言都非常有用,而不仅仅是 Python。 I would highly recommend installing.我强烈建议安装。

AREPL : Real-time Python scratchpad that displays your variables in a side window. AREPL :实时 Python 暂存器,在侧窗口中显示变量。 I'm the creator of this, so obviously I think it's great, but I can't give a unbiased opinion ¯\ (ツ)我是这个的创造者,所以显然我认为它很棒,但我不能给出公正的意见¯\ (ツ)

Wolf : Real-time Python scratchpad that displays results inline Wolf :实时显示结果的 Python 暂存器

And of course if you use the integrated terminal you can run Python code in there and not have to install any extensions.当然,如果您使用集成终端,您可以在其中运行 Python 代码,而无需安装任何扩展。

If you are using the latest version of Visual Studio Code ( version 1.21.1 ).如果您使用的是最新版本的 Visual Studio Code( 1.21.1 版)。 The task.json format has changed, see here . task.json格式已更改,请参见此处 So the answer by Fenton and by python_starter may no longer be valid.所以Fentonpython_starter的答案可能不再有效。

Before starting configuration开始配置之前

Before you start configuring Visual Studio Code for running your Python file.在开始配置 Visual Studio Code 以运行 Python 文件之前。

  • Make sure that you have installed Python and added its executable to your system PATH.确保您已安装 Python 并将其可执行文件添加到系统 PATH。
  • You must set the folder where your python source file resides as your working folder (go to File -> Open Folder to set your working folder).您必须将 python 源文件所在的文件夹设置为您的工作文件夹(转到File -> Open Folder以设置您的工作文件夹)。

Configuration steps配置步骤

Now you can configure the task.现在您可以配置任务了。 The following steps will help you run your python file correctly:以下步骤将帮助您正确运行 python 文件:

  1. use Ctrl + Shift + P and input task , you will see a list of options, select Tasks: Configure Task .使用Ctrl + Shift + P并输入task ,您将看到一个选项列表,选择Tasks: Configure Task

在此处输入图像描述

  1. You will then be prompted create task.json from template , choose this option, and you will be prompted to choose from a list of options.然后将提示您create task.json from template ,选择此选项,系统将提示您从选项列表中进行选择。 Choose Others .选择Others

在此处输入图像描述

  1. Then in the opened task.json file, use the following settings:然后在打开的task.json文件中,使用以下设置:

     { "version": "2.0.0", "tasks": [ { "label": "run this script", "type": "shell", "command": "python", "args": [ "${file}" ], "problemMatcher": [] } ] }

In the above settings, you can give a meaningful label to this task.在上面的设置中,你可以给这个任务一个有意义的label For example, run python .例如, run python

  1. Go to the Tasks menu and click Run Task .转到Tasks菜单并单击Run Task You will be prompted to choose the task.系统将提示您选择任务。 Just choose the newly created run this script task.只需选择新创建的run this script任务。 You will see the result in the TERMINAL tab.您将在“ TERMINAL ”选项卡中看到结果。

在此处输入图像描述

在此处输入图像描述

For a more complete tutorial about task configuration, go to the Visual Studio Code official documentation .如需更完整的任务配置教程,请访问Visual Studio Code 官方文档

Super simple:超级简单:

Press the F5 key and the code will run.F5键,代码将运行。

If a breakpoint is set, pressing F5 will stop at the breakpoint and run the code in debug mode.如果设置了断点,按F5将在断点处停止并在调试模式下运行代码。

Other Method - To add Shortcut其他方法 - 添加快捷方式

Note: You must have Python Extension By Microsoft installed in Visual Studio Code, and the Python interpreter selected in the lower-left corner.注意:您必须在 Visual Studio Code 中安装 Python Extension By Microsoft,并在左下角选择 Python 解释器。

Go to File → Preferences → Keyboard Shortcuts (alternatively, you can press Ctrl + K + S) In the search box, enter python.execInTerminal Double click that result (alternatively, you can click the plus icon) Press Ctrl + Alt + B to register this as the keybinding (alternatively, you can enter your own keybinding)转到文件 → 首选项 → 键盘快捷键(或者,您可以按 Ctrl + K + S)在搜索框中,输入 python.execInTerminal 双击该结果(或者,您可以单击加号图标)按 Ctrl + Alt + B 到将此注册为键绑定(或者,您可以输入自己的键绑定)

Now you can close the Keyboard Shortcuts tab Go to the Python file you want to run and press Ctrl + Alt + B (alternatively, you can press the keybinding you set) to run it.现在您可以关闭键盘快捷键选项卡转到您要运行的 Python 文件,然后按 Ctrl + Alt + B(或者,您可以按您设置的键绑定)来运行它。 The output will be shown in the bottom terminal tab.输出将显示在底部的终端选项卡中。

If I just want to run the Python file in the terminal, I'll make a keyboard shortcut for the command because there isn't one by default (you need to have the Python interpreter executable in your path):如果我只想在终端中运行 Python 文件,我将为该命令创建一个键盘快捷键,因为默认情况下没有快捷键(您需要在路径中包含 Python 解释器可执行文件):

  • Go to PreferencesKeyboard Shortcuts转到首选项键盘快捷键
  • Type 'run Python file in terminal'键入“在终端中运行 Python 文件”
  • Click on the '+' for that command and enter your keyboard shortcut单击该命令的“+”并输入您的键盘快捷键

I use Ctrl + Alt + N .我使用Ctrl + Alt + N

in new Version of VSCode (2019 and newer) We have run and debug Button for python,在新版本的 VSCode(2019 及更高版本)中,我们已经为 python 运行和调试按钮,

Debug :F5调试:F5

Run without Debug :Ctrl + F5不带调试运行:Ctrl + F5

So you can change it by go to File > Preferences > Keyboard Shortcuts search for RUN: start Without Debugging and change Shortcut to what you want.因此,您可以通过转到File > Preferences > Keyboard Shortcuts搜索RUN: start Without Debugging并将 Shortcut 更改为您想要的来更改它。 its so easy and work for Me (my VSCode Version is 1.51 but new update is available).它对我来说如此简单和工作(我的 VSCode 版本是 1.51,但有新的更新可用)。

I had installed Python via Anaconda .我已经通过Anaconda安装了 Python。

By starting Visual Studio Code via Anaconda I was able to run Python programs.通过 Anaconda 启动 Visual Studio Code,我能够运行 Python 程序。

However, I couldn't find any shortcut way (hotkey) to directly run .py files.但是,我找不到任何快捷方式(热键)来直接运行 .py 文件。

(Using the latest version as of Feb 21st 2019 with the Python extension which came with Visual Studio Code. Link: Python extension for Visual Studio Code ) (使用截至 2019 年 2 月 21 日的最新版本和 Visual Studio Code 附带的 Python 扩展。链接: Visual Studio Code 的 Python 扩展

The following worked:以下工作:

  1. Right clicking and selecting 'Run Python File in Terminal' worked for me.右键单击并选择“在终端中运行 Python 文件”对我有用。
  2. Ctrl + A then Shift + Enter (on Windows) Ctrl + A然后Shift + Enter (在 Windows 上)

The below is similar to what @jdhao did.以下与@jdhao 所做的类似。

This is what I did to get the hotkey:这是我为获取热键所做的:

  1. Ctrl + Shift + B // Run build task Ctrl + Shift + B // 运行构建任务
  2. It gives an option to configure它提供了一个配置选项
  3. I clicked on it to get more options.我单击它以获取更多选项。 I clicked on Other config我点击了其他配置
  4. A 'tasks.json' file opened 'tasks.json' 文件打开

I made the code look like this:我使代码看起来像这样:

    {
        // See https://go.microsoft.com/fwlink/?LinkId=733558
        // for the documentation about the tasks.json format
        "version": "2.0.0",
        "tasks": [
            {
                "label": "Run Python File", //this is the label I gave
                "type": "shell",
                "command": "python",
                "args": ["${file}"]

After saving it, the file changed to this:保存后,文件变成了这样:

    {
        // See https://go.microsoft.com/fwlink/?LinkId=733558
        // for the documentation about the tasks.json format
        "version": "2.0.0",
        "tasks": [
            {
                "label": "Run Python File",
                "type": "shell",
                "command": "python",
                "args": [
                    "${file}"
                ],
                "group": {
                    "kind": "build",
                    "isDefault": true
                }
            }
        ]
    }
  1. After saving the file 'tasks.json', go to your Python code and press Ctrl + Shift + B .保存文件“tasks.json”后,转到您的 Python 代码并按Ctrl + Shift + B
  2. Then click on Run taskRun Python File // This is the label that you gave.然后点击Run taskRun Python File // 这是你给的标签。

Now every time that you press Ctrl + Shift + B , the Python file will automatically run and show you the output :)现在每次按下Ctrl + Shift + B时,Python 文件都会自动运行并显示输出:)

Note: You must have Python Extension By Microsoft installed in Visual Studio Code, and the Python interpreter selected in the lower-left corner.注意:您必须在 Visual Studio Code 中安装Python Extension By Microsoft ,并在左下角选择 Python 解释器。

  1. Go to FilePreferencesKeyboard Shortcuts (alternatively, you can press Ctrl + K + S )转到文件首选项键盘快捷键(或者,您可以按Ctrl + K + S
  2. In the search box, enter python.execInTerminal在搜索框中,输入python.execInTerminal
  3. Double click that result (alternatively, you can click the plus icon)双击该结果(或者,您可以单击加号图标)
  4. Press Ctrl + Alt + B to register this as the keybinding (alternatively, you can enter your own keybinding)Ctrl + Alt + B将此注册为键绑定(或者,您可以输入自己的键绑定)
  5. Now you can close the Keyboard Shortcuts tab现在您可以关闭键盘快捷键选项卡
  6. Go to the Python file you want to run and press Ctrl + Alt + B (alternatively, you can press the keybinding you set) to run it.转到您要运行的 Python 文件,然后按Ctrl + Alt + B (或者,您可以按您设置的键绑定)来运行它。 The output will be shown in the bottom terminal tab.输出将显示在底部的终端选项卡中。

There is an easiest way to make a shortcut for run in terminal command:有一种最简单的方法可以为run in terminal创建快捷方式:

  1. Click on the settings icon on the left bar.单击左侧栏上的设置图标。
  2. Then click on Keyboard Shortcuts .然后点击Keyboard Shortcuts
  3. Paste python.execInTerminal in search bar on top.python.execInTerminal粘贴到顶部的搜索栏中。
  4. Now double-click on the Keybinding column opposite the Python: Run Python File in Terminal command and set the shortcut.现在双击Python: Run Python File in Terminal命令对面的Keybinding列并设置快捷方式。

I use Python 3.7 (32 bit).我使用 Python 3.7(32 位)。 To run a program in Visual Studio Code, I right-click on the program and select "Run Current File in Python Interactive Window".要在 Visual Studio Code 中运行程序,我右键单击该程序并选择“在 Python 交互窗口中运行当前文件”。 If you do not have Jupyter , you may be asked to install it.如果您没有Jupyter ,可能会要求您安装它。

在此处输入图像描述

A simple and direct Python extension would save both time and efforts.一个简单直接的Python 扩展将节省时间和精力。 Linting, debugging, code completion are the available features once installation is done.安装完成后,linting、调试、代码完成是可用的功能。 After this, to run the code proper Python installation path needs to be configured in order to run the code.在此之后,要运行代码,需要配置正确的 Python 安装路径才能运行代码。 General settings are available in User scope and Workspace can be configured for Python language– "python.pythonPath": "c:/python27/python.exe" With above steps at least the basic Python programs can be executed.通用设置用户范围内可用,工作空间可以配置为 Python 语言"python.pythonPath": "c:/python27/python.exe"通过上述步骤,至少可以执行基本的 Python 程序。

If you are running code and want to take input via running your program in the terminal, the best thing to do is to run it in terminal directly by just right click and choose "Run Python File in Terminal".如果您正在运行代码并希望通过在终端中运行程序来获取输入,最好的办法是直接在终端中运行它,只需右键单击并选择“在终端中运行 Python 文件”。

在此处输入图像描述

From Extensions , install Code Runner .Extensions安装Code Runner After that you can use the shortcuts to run your source code in Visual Studio Code.之后,您可以使用快捷方式在 Visual Studio Code 中运行您的源代码。

First: To run code:第一:运行代码:

  • use shortcut Ctrl + Alt + N使用快捷键Ctrl + Alt + N
  • or press F1 and then select/type Run Code ,或按F1然后选择/键入Run Code ,
  • or right click in a text editor window and then click Run Code in the editor context menu或右键单击文本编辑器窗口,然后单击编辑器上下文菜单中的运行代码
  • or click the Run Code button in editor title menu (triangle to the right)或单击编辑器标题菜单中的“运行代码”按钮(右侧的三角形)
  • or click Run Code in context menu of file explorer.或单击文件资源管理器上下文菜单中的运行代码

Second: To stop the running code:第二:停止正在运行的代码:

  • use shortcut Ctrl + Alt + M使用快捷键Ctrl + Alt + M
  • or press F1 and then select/type Stop Code Run或按F1然后选择/键入Stop Code Run
  • or right click the Output Channel and then click Stop Code Run in the context menu或右键单击输出通道,然后单击上下文菜单中的停止代码运行

If you install Python language extension for VSCode, it also installs Jupyter and Pylance by default, which lets you run Python code in interactive manner.如果你为 VSCode 安装 Python 语言扩展,它也会默认安装 Jupyter 和 Pylance,让你以交互方式运行 Python 代码。

All you have to do is use # %% before the code that you want to execute interactively.您所要做的就是在要交互执行的代码之前使用# %%

As soon as you insert # %% , you can see that VSCode creates a new Jupyter Cell for you.插入# %%后,您可以看到 VSCode 为您创建了一个新的 Jupyter Cell。

在此处输入图像描述

And from there you can click on the Run Cell cell menu and you can see the result.从那里您可以单击“ Run Cell格”单元格菜单,您可以看到结果。

So, all you have to do is type the following code in your VSCode,所以,你所要做的就是在你的 VSCode 中输入以下代码,

# %%
text = 'Hello World from inline interactive Python'
print(text)

  • Press F5 to run with DebuggingF5运行调试
  • Press Ctrl + F5 to run with Debugging ignoring breakpoints.Ctrl + F5以调试忽略断点运行。

Running the current python file as is does not have a keybinding associated by default, but you can set this with:默认情况下,按原样运行当前 python 文件没有关联的键绑定,但您可以使用以下命令进行设置:

  1. Ctrl + Shift + P Ctrl + Shift + P
  2. Type "Run Python file in Terminal"键入“在终端中运行 Python 文件”
  3. Hover over it and click the ⚙️ icon将鼠标悬停在它上面并单击⚙️图标
  4. Double click "Keybinding"双击“键绑定”
  5. Set your desired shortcut设置您想要的快捷方式

In order to launch the current file with the respective venv , I added this to file launch.json :为了使用相应的venv启动当前文件,我将其添加到文件launch.json

 {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "pythonPath": "${workspaceFolder}/FOO/DIR/venv/bin/python3"
    },

In the bin folder resides the source .../venv/bin/activate script which is regularly sourced when running from a regular terminal. bin文件夹中包含source .../venv/bin/activate脚本,该脚本在从常规终端运行时定期获取。

If you have a project consisting of multiple Python files and you want to start running/debugging with the main program independent of which file is current you create the following launch configuration (change MyMain.py to your main file).如果您有一个由多个 Python 文件组成的项目,并且您想使用主程序开始运行/调试,而与当前文件无关,您可以创建以下启动配置(将MyMain.py更改为您的主文件)。

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Main File",
      "type": "python",
      "request": "launch",
      "program": "${workspaceFolder}/MyMain.py",
      "console": "integratedTerminal",
      "cwd": "${workspaceFolder}"
    }
  ]
}
  1. First of all you need to install an extension called "Code Runner"首先你需要安装一个名为“Code Runner”的扩展
  2. After then look at the right top corner of Visual Studio Code, you will see the run button and hit that.然后查看 Visual Studio Code 的右上角,您将看到运行按钮并点击它。
  3. After that you will see at the bottom of vs code your code has been executed.之后,您将在 vs code 的底部看到您的代码已被执行。
  4. You can make your own keyboard shortcut for "Code Runner" to speed up your coding.您可以为“Code Runner”制作自己的键盘快捷键以加快编码速度。

I used my existing anaconda environment to run python.我使用我现有的 anaconda 环境来运行 python。 rather than using the python user appdata\local\programs\python use the anaconda install python by environment.而不是使用 python 用户 appdata\local\programs\python 使用 anaconda install python by environment。 This will give you access to all your libraries in the environment.这将使您可以访问环境中的所有库。

 1. View->Command Palette->Open user settings
 2. search python
 a. Python: default interpreter path = c:\users\yourname\Anaconda3\python.exe
 b. save the file
 3. View->Command Palette->python:select interpreter
 a. arrow down to your workspace name
 b. select your python and environment

 create a python script and run it.

 see https://code.visualstudio.com/docs/python/environments

One workaround is to the following :一种解决方法是:

  • Select all the lines : Ctrl + A选择所有行: Ctrl + A
  • Run the selected lines : Shift + Enter运行选定的行: Shift + Enter

To run python3 on windows vs code:要在 windows vs 代码上运行python3

  1. Download the python interpreter from their official site从他们的官方网站下载 python 解释器

  2. Install the python packages for vs code.为 vs 代码安装python 包 This can be installed directly from vscode's extension manager这可以直接从 vscode 的扩展管理器安装

  3. Verify that your python3 has been installed by running this command:通过运行以下命令验证您的 python3 是否已安装:

    py -3 --version py -3 --版本

  4. Run your script with the following command from vscode's terminal:从 vscode 的终端使用以下命令运行脚本:

    py -3 main.py py -3 main.py

For more information, head over here for details installation procedure.有关更多信息,请前往此处了解详细安装过程。

On your Mac use control+F5(fn+F5)在 Mac 上使用 control+F5(fn+F5)

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

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