Visual Studio Code最近发布了,我喜欢它的外观和提供的功能,所以我想尝试一下。
我从下载页面下载了应用程序,启动了它,对一些功能做了一些调整……然后意识到我不知道如何实际执行我的任何Python代码!
我真的很喜欢Visual Studio代码的外观和感觉/可用性/特性,但我似乎不知道如何运行我的Python代码,这是一个真正的杀手,因为我主要用Python编程。
是否有一种方法可以在Visual Studio code中执行Python代码?
Visual Studio Code最近发布了,我喜欢它的外观和提供的功能,所以我想尝试一下。
我从下载页面下载了应用程序,启动了它,对一些功能做了一些调整……然后意识到我不知道如何实际执行我的任何Python代码!
我真的很喜欢Visual Studio代码的外观和感觉/可用性/特性,但我似乎不知道如何运行我的Python代码,这是一个真正的杀手,因为我主要用Python编程。
是否有一种方法可以在Visual Studio code中执行Python代码?
当前回答
如果你为VSCode安装了Python语言扩展,它默认也会安装Jupyter和Pylance,这让你可以以交互的方式运行Python代码。
您所要做的就是在希望以交互方式执行的代码之前使用# %%。
只要你插入# %%,你就可以看到VSCode为你创建了一个新的Jupyter Cell。
在那里你可以点击运行单元格菜单,你可以看到结果。
所以,你所要做的就是在你的VSCode中输入以下代码,
# %%
text = 'Hello World from inline interactive Python'
print(text)
其他回答
如果你有一个由多个Python文件组成的项目,并且你想用主程序开始运行/调试,而不依赖于当前的哪个文件,你可以创建以下启动配置(将MyMain.py更改为你的主文件)。
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Main File",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/MyMain.py",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}"
}
]
}
在Visual Studio Code (Python)的最新版本(1.36)中:
按F5,然后按Enter,在集成终端中运行代码。
按Ctrl + A,然后按Shift + Enter,在交互式IPython shell中运行代码。
下面是如何在Visual Studio Code中配置任务运行器以运行.py文件。
在控制台中,按Ctrl + Shift + P (Windows)或Cmd + Shift + P (Apple)。这将出现一个搜索框,您可以在其中搜索“配置任务运行器”
如果这是第一次打开“任务:配置任务运行器”,则需要在下一个选择列表底部选择“其他”。
这将打开属性,然后您可以更改以适应您的偏好。在本例中,您希望更改以下属性;
将Command属性从"tsc" (TypeScript)更改为"Python" 将showOutput从"silent"修改为"Always" 将args (Arguments)从["Helloworld. "Ts "]到["${文件}"](文件名) 删除最后一个属性problemMatcher 保存所做的更改
您现在可以打开您的.py文件,并使用快捷键Ctrl + Shift + B (Windows)或Cmd + Shift + B (Apple)很好地运行它。
超级简单:
按下F5键,代码将运行。
如果设置了断点,按F5将在断点处停止,并在调试模式下运行代码。
其他方法-添加快捷方式
注意:你必须在Visual Studio Code中安装Python Extension By Microsoft,并在左下角选择Python解释器。
选择文件→首选项→键盘快捷键(也可以按Ctrl + K + S) 在搜索框中输入python. execterminal 双击该结果(或者,可以单击加号图标) 按Ctrl + Alt + B将其注册为键绑定(或者,您可以输入自己的键绑定)
现在您可以关闭键盘快捷键选项卡 转到您想要运行的Python文件,并按Ctrl + Alt + B(或者,您可以按下您设置的键绑定)来运行它。输出将显示在底部的终端选项卡中。
注意:你必须在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.