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

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

我真的很喜欢Visual Studio代码的外观和感觉/可用性/特性,但我似乎不知道如何运行我的Python代码,这是一个真正的杀手,因为我主要用Python编程。

是否有一种方法可以在Visual Studio code中执行Python代码?


当前回答

如果我只是想在终端中运行Python文件,我会为该命令创建一个键盘快捷方式,因为默认情况下没有快捷方式(你需要在你的路径中有Python解释器可执行文件):

进入首选项(左下角的齿轮图标)→键盘快捷键 输入“在终端中运行Python文件” 点击该命令的“+”,然后输入键盘快捷键

我用Ctrl + Alt + N。

其他回答

注意:你必须在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) 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. The output will be shown in the bottom terminal tab.

以下是当前(2018年9月)用于运行Python代码的扩展:

官方Python扩展:这是必须安装的。

代码运行器:对各种语言都非常有用,不仅仅是Python。我强烈推荐安装。

实时Python便签,在侧窗口中显示你的变量。我是这个的创建者,所以显然我认为它很棒,但我不能给出一个公正的意见¯\()/¯

Wolf:实时Python便签,内联显示结果

当然,如果你使用集成的终端,你可以在那里运行Python代码,而不必安装任何扩展。

首先,你需要安装一个名为“代码运行器”的扩展 然后看看Visual Studio Code的右上角,你会看到运行按钮和 打击。 之后,你会在vs code的底部看到你的代码已经被执行。 您可以为“代码运行器”创建自己的键盘快捷键,以加快编码速度。

如果你为VSCode安装了Python语言扩展,它默认也会安装Jupyter和Pylance,这让你可以以交互的方式运行Python代码。

您所要做的就是在希望以交互方式执行的代码之前使用# %%。

只要你插入# %%,你就可以看到VSCode为你创建了一个新的Jupyter Cell。

在那里你可以点击运行单元格菜单,你可以看到结果。

所以,你所要做的就是在你的VSCode中输入以下代码,

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

我使用我现有的anaconda环境来运行python。而不是使用python用户appdata\local\programs\python使用anaconda install python by 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