Visual Studio 2022中Python代码片段运行及快捷键设置问题
在Visual Studio 2022中运行Python选中代码片段并设置快捷键
1. 运行选中的代码片段
- 打开目标Python文件(如
module1.py),选中需要执行的代码(比如print("hello1")) - 右键选中区域,选择 "Run Selection/Line in Python Interactive":代码会在Python交互窗口执行,仅运行选中部分,不会触发未选中的代码(如
print("hello2")) - 若偏好终端执行,右键选择 "Execute in Python Terminal",选中代码会在集成终端中直接运行
2. 设置自定义快捷键
- 依次打开
Tools > Options > Environment > Keyboard - 在「Show commands containing」输入框中,搜索对应命令:
- 交互窗口运行:
Python.RunSelectionInInteractive - 终端运行:
Python.ExecuteSelectionInTerminal
- 交互窗口运行:
- 选中目标命令后,在「Press shortcut keys」输入你想要的快捷键(比如
Ctrl+Shift+Enter),点击「Assign」后保存设置
3. 确保仅执行当前标签页代码
上述两种执行方式默认仅读取当前激活标签页中你选中的代码内容,不会关联其他打开的标签页文件,满足你只运行module1.py中选中代码的需求
内容的提问来源于stack exchange,提问作者JoshK
相关产品推荐
相关产品推荐

