使用 Python 交互窗口Work with the Python Interactive window
02/11/2019
本文内容
Visual Studio 为每个 Python 环境提供交互读取-评估-打印-循环 (REPL) 窗口,改进了在命令行中运行 python.exe 获得的 REPL。Visual Studio provides an interactive read-evaluate-print loop (REPL) window for each of your Python environments, which improves upon the REPL you get with python.exe on the command line. 借助交互窗口(通过“视图” > “其他窗口” > “<环境>交互”菜单命令打开),可以输入任意 Python 代码,并查看即时结果。The Interactive window (opened with the View > Other Windows > Interactive menu commands) lets you enter arbitrary Python code and see immediate results. 这种编码方式有助于了解与实验 API 和库,并以交互方式开发要包含在项目中的工作代码。This way of coding helps you learn and experiment with APIs and libraries, and to interactively develop working code to include in your projects.
Visual Studio 有大量 Python REPL 模式可供选择:Visual Studio has a number of Python REPL modes to choose from:
REPLREPL
描述Description
编辑Editing
调试Debugging
映像Images
标准Standard
默认 REPL,直接与 Python 通信Default REPL, talks to Python directly
标准编辑(多行等)。Standard editing (multiline, etc.).
是,通过 $attachYes, via $attach
否No
调试Debug
默认 REPL,与已调试的 Python 进程通信Default REPL, talks to debugged Python process
标准编辑Standard editing
仅调试Only debugging
否No
IPythonIPython
REPL 与 IPython 后端通信REPL talks to IPython backend
IPython 命令,Pylab 的便利IPython commands, Pylab conveniences
否No
是,在 REPL 中内联Yes, inline in REPL
带 Pylab 的 IPythonIPython w/o Pylab
REPL 与 IPython 后端通信REPL talks to IPython backend
标准 IPythonStandard IPython
否No
是,单独窗口Yes, separate window
本文介绍标准 REPL 模式和调试 REPL 模式。This article describes the Standard and Debug REPL modes. 有关 IPython 模式的详细信息,请参阅使用 IPython REPL。For details on IPython modes, see Use the IPython REPL.
有关包含示例的详细演练,包括与编辑器的交互(如 Ctrl+Enter),请参阅教程步骤 3 :使用交互 REPL 窗口。For a detailed walkthrough with examples, including the interactions with the editor such as Ctrl+Enter, see Tutorial Step 3: Use the Interactive REPL window.
打开交互窗口Open an Interactive window
以下有几种方法可用于针对某个环境打开交互窗口。There are several ways to open the Interactive window for an environment.
方法一,切换到 Python 环境窗口(“视图” > “其他窗口” > “Python 环境”或 Ctrl+K > Ctrl+`),然后针对选定的环境,选择“打开交互窗口”命令或按钮。First, switch to the Python Environments window (View > Other Windows > Python Environments or Ctrl+K > Ctrl+`) and select the Open Interactive Window command or button for a chosen environment.
方法二,在“视图” > “其他窗口”菜单底部附近,可以针对默认环境使用“Python 交互窗口”命令,另外还有一个命令可用于切换到环境窗口:Second, near the bottom of the View > Other Windows menu, there's a Python Interactive Window command for your default environment, as well as a command to switch to the Environments window:
方法三,可以通过选择“调试” > “在 Python 交互窗口中执行 ”菜单命令 (Shift+Alt+F5),打开项目中启动文件的“交互”窗口,或独立文件的“交互”窗口 :Third, you can open an Interactive window on the startup file in your project, or for a stand-alone file, by selecting the Debug > Execute in Python Interactive menu command (Shift+Alt+F5):
最后,可以选中文件中的代码,然后如下所述,使用发送到交互命令。Finally, you can select code in file and use the Send to Interactive command described below.
交互窗口选项Interactive window options
可以通过“工具” > “选项” > “Python” > “交互窗口”控制“交互”窗口的各个方面(请参阅选项):You can control various aspects of the Interactive window through Tools > Options > Python > Interactive Windows (see Options):
使用交互窗口Use the Interactive window
交互窗口打开后,可以在 >>> 提示符处逐行输入代码。Once the Interactive window is open, you can start entering code line-by-line at the >>> prompt. 交互窗口会执行输入的每一行代码,包括导入模块、定义变量等:The Interactive window executes each line as you enter it, which includes importing modules, defining variables, and so on:
例外情况是需要其他行的代码才能补全语句,例如 for 语句以冒号结束,如上所示。The exception is when additional lines of code are needed to make a complete statement, such as when a for statement ends in a colon as shown above. 在这些情况下,行提示符将更改为 ...,指示需要输入程序块的其他行,如上图中的第四和第五行所示。In these cases, the line prompt changes to ... indicating that you need to enter additional lines for the block, as shown on the fourth and fifth lines in the graphic above. 在空白行上按 Enter 键时,交互窗口会关闭程序块,并在解释器中运行该程序块。When you press Enter on a blank line, the Interactive window closes the block and runs it in the interpreter.
提示
交互窗口通过自动缩进属于周边范围的语句,改进常用 Python 命令行的 REPL 体验。The Interactive window improves upon the usual Python command-line REPL experience by automatically indenting statements that belong to a surrounding scope. 其历史记录(使用向上键重新调用)还提供多行项,而命令行 REPL 仅提供单行。Its history (recalled with the up arrow) also provides multiline items, whereas the command-line REPL provides only single lines.
交互窗口还支持多个元命令。The Interactive window also supports several meta-commands. 所有元命令都以 $ 开头,你可以键入 $help 获得元命令和 $help 的列表,以获取特定命令的使用情况详细信息。All meta-commands start with $, and you can type $help to get a list of the meta-commands and $help to get usage details for a specific command.
元命令Meta-command
描述Description
$$
插入注释,用于注释会话中的代码。Inserts a comment, which is helpful to comment code throughout your session.
$attach
将 Visual Studio 调试器附加到 REPL 窗口进程以启用调试。Attaches the Visual Studio debugger to the REPL window process to enable debugging.
$cls,$clear$cls, $clear
清除编辑器窗口的内容,使历史记录和执行上下文保持不变。Clears the contents of the editor window, leaving history and execution context intact.
$help
显示命令列表,或有关特定命令的帮助。Display a list of commands, or help on a specific command.
$load
从文件加载命令并执行,直到完成。Loads commands from file and executes until complete.
$mod
将当前范围切换为指定模块名称。Switches the current scope to the specified module name.
$reset
将执行环境重置为初始状态,但保留历史记录。Resets the execution environment to the initial state, but keeps history.
$wait
至少等待指定的毫秒数。Waits for at least the specified number of milliseconds.
Visual Studio 扩展还可以通过实现和导出 IInteractiveWindowCommand 来扩展命令(示例)。Commands are also extensible by Visual Studio extensions by implementing and exporting IInteractiveWindowCommand (example).
切换范围Switch scopes
默认情况下,项目交互窗口的范围为项目的启动文件,就像从命令提示符处运行一样。By default, the Interactive window for a project is scoped to the project's startup file as if you ran it from the command prompt. 对于独立文件,其范围为该文件。For a stand-alone file, it scopes to that file. 但是,在 REPL 会话期间,可随时使用交互窗口顶部的下拉列表菜单更改范围:At any time during your REPL session, however, the drop-down menu along the top of the Interactive window lets you change scope:
导入模块后(如键入 import importlib),下拉列表中将显示可切换到该模块任意范围的选项。Once you import a module, such as typing import importlib, options appear in the drop-down to switch into any scope in that module. 交互窗口中的消息还会指示新的范围,可用于跟踪会话期间如何达到某个特定状态。A message in the Interactive window also indicates the new scope, so you can track how you got to a certain state during your session.
在某个范围中输入 dir() 将显示该范围的有效标识符,包括函数名称、类和变量。Entering dir() in a scope displays valid identifiers in that scope, including function names, classes, and variables. 例如,使用 import importlib 后跟 dir() 将显示以下内容:For example, using import importlib followed by dir() shows the following:
发送到交互命令Send to Interactive command
除了直接在交互窗口中处理代码,还可以在编辑器中选中代码,单击右键,并选择“发送到交互”,或按 Ctrl+Enter。In addition to working within the Interactive window directly, you can select code in the editor, right-click, and choose Send to Interactive or press Ctrl+Enter.
此命令非常适用于迭代或演化代码开发,包括在开发时测试代码。This command is useful for iterative or evolutionary code development, including testing your code as you develop it. 例如,将一段代码发送到交互窗口并显示其输出后,可以按向上键再次显示代码、对其进行修改,并通过按 Ctrl+Enter 快速测试。For example, once you've sent a piece of code to the Interactive window and seen its output, you can press the up arrow to show the code again, modify it, and test it quickly by pressing Ctrl+Enter. (在输入结束时按 Enter 将执行它,但在输入过程中按 Enter 将插入新行。)如果有需要的代码,可以轻松将其复制回项目文件。(Pressing Enter at the end of input executes it, but pressing Enter in the middle of input inserts a newline.) Once you have the code you want, you can easily copy it back into your project file.
提示
Visual Studio 默认会删除 >>> 和 ...将代码从交互窗口粘贴到编辑器时,REPL 会发出提示。By default, Visual Studio removes >>> and ... REPL prompts when pasting code from the Interactive window into the editor. 可以在“工具” > “选项” > “文本编辑器” > “Python” > “高级”选项卡上使用“粘贴删除 REPL 提示”选项更改此行为。You can change this behavior on the Tools > Options > Text Editor > Python > Advanced tab using the Paste removes REPL prompts option.
使用代码单元Work with code cells
代码单元可用于数据分析,并且受到各种文本编辑器支持。Code cells can be used in data analysis and are supported by a variety of text editors.
例如,将代码文件用作暂存器时,通常有一小部分代码块需要一次性全部发送。For example, when using a code file as a scratchpad, you often have a small block of code you want to send all at once. 为了汇集代码,可以在单元开头添加以 #%% 开头的注释,将代码标记为代码单元,结束前一个代码单元。To group code together, mark the code as a code cell by adding a comment starting with #%% to the beginning of the cell, which ends the previous one. 代码单元可以折叠和展开,在代码单元内使用 Ctrl+Enter 会将整个单元发送到交互窗口并移动到下一个代码单元。Code cells can be collapsed and expanded, and using Ctrl+Enter inside a code cell sends the entire cell to the Interactive window and moves to the next one.
Visual Studio 还会检测以 # In[1]: 等注释开头的代码单元,将 Jupyter 笔记本导出为 Python 文件时会获得这种格式。Visual Studio also detects code cells starting with comments like # In[1]:, which is the format you get when exporting a Jupyter notebook as a Python file. 通过此次检测,可以轻松地运行 Azure Notebooks 的笔记本,只需下载为 Python 文件,在 Visual Studio 中打开并使用 Ctrl+Enter 运行每个单元即可。This detection makes it easy to run a notebook from Azure Notebooks by downloading as a Python file, opening in Visual Studio, and using Ctrl+Enter to run each cell.
IntelliSense 的行为IntelliSense behavior
与代码编辑器中 IntelliSense 仅基于源代码分析不同,交互窗口中,IntelliSense 基于活动的对象。The Interactive window includes IntelliSense based on the live objects, unlike the code editor in which IntelliSense is based on source code analysis only. 这些建议在交互窗口中更为正确,尤其是在使用动态生成代码的情况下。These suggestions are more correct in the Interactive window, especially with dynamically generated code. 缺点是具有副作用(如记录消息)的函数可能会影响开发体验。The drawback is that functions with side-effects (such as logging messages) may impact your development experience.
如果此行为造成了困扰,请在“完成模式”组的“工具” > “选项” > “Python” > “交互窗口”下更改设置,如选项 - 交互窗口选项所述。If this behavior is a problem, change the settings under Tools > Options > Python > Interactive Windows in the Completion Mode group, as described on Options - Interactive windows options.