IDLE

Source code: Lib/idlelib/


IDLE is Python’s Integrated Development and Learning Environment.IDLE是Python的集成开发和学习环境。

IDLE has the following features:IDLE具有以下功能:

  • coded in 100% pure Python, using the tkinter GUI toolkit使用tkinter GUI工具包以100%纯Python编码

  • cross-platform: works mostly the same on Windows, Unix, and macOS跨平台:在Windows、Unix和macOS上基本相同

  • Python shell window (interactive interpreter) with colorizing of code input, output, and error messagesPython shell窗口(交互式解释器),带有代码输入、输出和错误消息的着色

  • multi-window text editor with multiple undo, Python colorizing, smart indent, call tips, auto completion, and other features具有多重撤销、Python着色、智能缩进、调用提示、自动完成和其他功能的多窗口文本编辑器

  • search within any window, replace within editor windows, and search through multiple files (grep)在任何窗口中搜索,在编辑器窗口中替换,并搜索多个文件(grep)

  • debugger with persistent breakpoints, stepping, and viewing of global and local namespaces具有持久断点、单步执行和查看全局和本地命名空间的调试器

  • configuration, browsers, and other dialogs配置、浏览器和其他对话框

Editing and navigation编辑和导航

Editor windows编辑器窗口

IDLE may open editor windows when it starts, depending on settings and how you start IDLE. IDLE启动时可能会打开编辑器窗口,具体取决于设置和启动IDLE的方式。Thereafter, use the File menu. 然后,使用文件菜单。There can be only one open editor window for a given file.给定文件只能有一个打开的编辑器窗口。

The title bar contains the name of the file, the full path, and the version of Python and IDLE running the window. 标题栏包含文件名、完整路径以及运行窗口的Python和IDLE版本。The status bar contains the line number (‘Ln’) and column number (‘Col’). 状态栏包含行号(“Ln”)和列号(“Col”)。Line numbers start with 1; column numbers with 0.行号以1开头;列编号为0。

IDLE assumes that files with a known .py* extension contain Python code and that other files do not. IDLE假设扩展名为.py*的文件包含Python代码,而其他文件则不包含。Run Python code with the Run menu.使用Run菜单运行Python代码。

Key bindings键绑定

In this section, ‘C’ refers to the Control key on Windows and Unix and the Command key on macOS.在本节中,“C”是指Windows和Unix上的Control键和macOS上的Command键。

  • Backspace deletes to the left; 向左删除;Del deletes to the right向右删除

  • C-Backspace delete word left; 删除左边的单词;C-Del delete word to the right删除右边的单词

  • Arrow keys and Page Up/Page Down to move around

  • C-LeftArrow and C-RightArrow moves by words

  • Home/End go to begin/end of line

  • C-Home/C-End go to begin/end of file

  • Some useful Emacs bindings are inherited from Tcl/Tk:一些有用的Emacs绑定继承自Tcl/Tk:

    • C-a beginning of line

    • C-e end of line

    • C-k kill line (but doesn’t put it in clipboard)

    • C-l center window around the insertion point

    • C-b go backward one character without deleting (usually you can also use the cursor key for this)

    • C-f go forward one character without deleting (usually you can also use the cursor key for this)

    • C-p go up one line (usually you can also use the cursor key for this)

    • C-d delete next character

Standard keybindings (like C-c to copy and C-v to paste) may work. 标准键绑定(如C-c复制和C-v粘贴)可能会起作用。Keybindings are selected in the Configure IDLE dialog.在“配置空闲”对话框中选择键绑定。

Automatic indentation自动缩进

After a block-opening statement, the next line is indented by 4 spaces (in the Python Shell window by one tab). 在块打开语句之后,下一行缩进4个空格(在Python Shell窗口中,缩进一个选项卡)。After certain keywords (break, return etc.) the next line is dedented. 在某些关键字(break、return等)之后,将删除下一行。In leading indentation, Backspace deletes up to 4 spaces if they are there. Tab inserts spaces (in the Python Shell window one tab), number depends on Indent width. Currently, tabs are restricted to four spaces due to Tcl/Tk limitations.目前,由于Tcl/Tk的限制,选项卡被限制为四个空格。

See also the indent/dedent region commands on the Format menu.另请参见“格式”菜单上的“缩进/删除区域”命令。

Completions补全

Completions are supplied, when requested and available, for module names, attributes of classes or functions, or filenames. 在请求和可用时,为模块名、类或函数的属性或文件名提供补全。Each request method displays a completion box with existing names. 每个请求方法都显示一个包含现有名称的完成框。(See tab completions below for an exception.) (有关例外情况,请参阅下面的选项卡完成。)For any box, change the name being completed and the item highlighted in the box by typing and deleting characters; by hitting Up, Down, PageUp, PageDown, Home, and End keys; and by a single click within the box. Close the box with Escape, Enter, and double Tab keys or clicks outside the box. A double click within the box selects and closes.在框内双击可选择并关闭。

One way to open a box is to type a key character and wait for a predefined interval. 打开框的一种方法是键入关键字符并等待预定义的间隔。This defaults to 2 seconds; customize it in the settings dialog. 默认为2秒;在“设置”对话框中进行自定义。(To prevent auto popups, set the delay to a large number of milliseconds, such as 100000000.) (要防止自动弹出,请将延迟设置为大量毫秒,例如100000000。)For imported module names or class or function attributes, type ‘.’. 对于导入的模块名或类或函数属性,请键入“.”。For filenames in the root directory, type os.sep or os.altsep immediately after an opening quote. 对于根目录中的文件名,请在开头引号后立即键入os.sepos.altsep(On Windows, one can specify a drive first.) (在Windows上,可以先指定驱动器。)Move into subdirectories by typing a directory name and a separator.通过键入目录名和分隔符移动到子目录中。

Instead of waiting, or after a box is closed, open a completion box immediately with Show Completions on the Edit menu. 不要等待,或在框关闭后,立即打开“编辑”菜单上的“显示完成”框。The default hot key is C-space. If one types a prefix for the desired name before opening the box, the first match or near miss is made visible. 如果在打开框之前键入所需名称的前缀,则会显示第一个匹配或未遂。The result is the same as if one enters a prefix after the box is displayed. 结果与显示框后输入前缀的结果相同。Show Completions after a quote completes filenames in the current directory instead of a root directory.在引号完成当前目录(而不是根目录)中的文件名后显示完成。

Hitting Tab after a prefix usually has the same effect as Show Completions. (With no prefix, it indents.) However, if there is only one match to the prefix, that match is immediately added to the editor text without opening a box.

Invoking ‘Show Completions’, or hitting Tab after a prefix, outside of a string and without a preceding ‘.’ opens a box with keywords, builtin names, and available module-level names.

When editing code in an editor (as oppose to Shell), increase the available module-level names by running your code and not restarting the Shell thereafter. 在编辑器中编辑代码(与Shell相反)时,通过运行代码而不重新启动Shell来增加可用的模块级名称。This is especially useful after adding imports at the top of a file. 在文件顶部添加导入后,这尤其有用。This also increases possible attribute completions.这也增加了可能的属性完成。

Completion boxes initially exclude names beginning with ‘_’ or, for modules, not included in ‘__all__’. The hidden names can be accessed by typing ‘_’ after ‘.’, either before or after the box is opened.

Calltips调用提示

A calltip is shown automatically when one types ( after the name of an accessible function. A function name expression may include dots and subscripts. A calltip remains until it is clicked, the cursor is moved out of the argument area, or ) is typed. Whenever the cursor is in the argument part of a definition, select Edit and “Show Call Tip” on the menu or enter its shortcut to display a calltip.

The calltip consists of the function’s signature and docstring up to the latter’s first blank line or the fifth non-blank line. 调用提示由函数的签名和docstring组成,直到后者的第一个空行或第五个非空行。(Some builtin functions lack an accessible signature.) (某些内置函数缺少可访问签名。)A ‘/’ or ‘*’ in the signature indicates that the preceding or following arguments are passed by position or name (keyword) only. 签名中的“/”或“*”表示前面或后面的参数仅通过位置或名称(关键字)传递。Details are subject to change.详情可能会更改。

In Shell, the accessible functions depends on what modules have been imported into the user process, including those imported by Idle itself, and which definitions have been run, all since the last restart.在Shell中,可访问的函数取决于用户进程中导入了哪些模块,包括Idle本身导入的模块,以及自上次重启以来运行了哪些定义。

For example, restart the Shell and enter itertools.count(. A calltip appears because Idle imports itertools into the user process for its own use. 出现调用提示是因为Idle将itertools导入用户进程以供自己使用。(This could change.) Enter turtle.write( and nothing appears. Idle does not itself import turtle. The menu entry and shortcut also do nothing. Enter import turtle. Thereafter, turtle.write( will display a calltip.

In an editor, import statements have no effect until one runs the file. 在编辑器中,导入语句在运行文件之前无效。One might want to run a file after writing import statements, after adding function definitions, or after opening an existing file.您可能希望在编写导入语句、添加函数定义或打开现有文件后运行文件。

Code Context代码上下文

Within an editor window containing Python code, code context can be toggled in order to show or hide a pane at the top of the window. 在包含Python代码的编辑器窗口中,可以切换代码上下文,以便在窗口顶部显示或隐藏窗格。When shown, this pane freezes the opening lines for block code, such as those beginning with class, def, or if keywords, that would have otherwise scrolled out of view. 显示时,此窗格将冻结块代码的开头行,例如以classdefif关键字开头的代码,否则这些代码将滚动出视图。The size of the pane will be expanded and contracted as needed to show the all current levels of context, up to the maximum number of lines defined in the Configure IDLE dialog (which defaults to 15). 窗格的大小将根据需要展开和缩小,以显示所有当前级别的上下文,最多可显示“配置空闲”对话框中定义的最大行数(默认为15)。If there are no current context lines and the feature is toggled on, a single blank line will display. Clicking on a line in the context pane will move that line to the top of the editor.如果没有当前上下文行且功能处于打开状态,则将显示一个空行。单击上下文窗格中的一行将该行移动到编辑器的顶部。

The text and background colors for the context pane can be configured under the Highlights tab in the Configure IDLE dialog.上下文窗格的文本和背景颜色可以在“配置空闲”对话框的“突出显示”选项卡下配置。

Python Shell windowPython外壳窗口

With IDLE’s Shell, one enters, edits, and recalls complete statements. 使用IDLE的Shell,可以输入、编辑和调用完整的语句。Most consoles and terminals only work with a single physical line at a time.大多数控制台和终端一次只能使用一条物理线路。

When one pastes code into Shell, it is not compiled and possibly executed until one hits Return. One may edit pasted code first. If one pastes more that one statement into Shell, the result will be a SyntaxError when multiple statements are compiled as if they were one.

The editing features described in previous subsections work when entering code interactively. 前面小节中描述的编辑功能在以交互方式输入代码时起作用。IDLE’s Shell window also responds to the following keys.IDLE的Shell窗口还响应以下键。

  • C-c interrupts executing command

  • C-d sends end-of-file; closes window if typed at a >>> prompt

  • Alt-/ (Expand word) is also useful to reduce typing

    Command history

    • Alt-p retrieves previous command matching what you have typed. On macOS use C-p.

    • Alt-n retrieves next. On macOS use C-n.

    • Return while on any previous command retrieves that command

Text colors文本颜色

Idle defaults to black on white text, but colors text with special meanings. For the shell, these are shell output, shell error, user output, and user error. For Python code, at the shell prompt or in an editor, these are keywords, builtin class and function names, names following class and def, strings, and comments. For any text window, these are the cursor (when present), found text (when possible), and selected text.

IDLE also highlights the soft keywords match, case, and _ in pattern-matching statements. However, this highlighting is not perfect and will be incorrect in some rare cases, including some _-s in case patterns.

Text coloring is done in the background, so uncolorized text is occasionally visible. 文本着色是在背景中完成的,因此未着色的文本偶尔可见。To change the color scheme, use the Configure IDLE dialog Highlighting tab. 要更改颜色方案,请使用“配置空闲对话框高亮显示”选项卡。The marking of debugger breakpoint lines in the editor and text in popups and dialogs is not user-configurable.在编辑器中标记调试器断点行以及在弹出窗口和对话框中标记文本是用户无法配置的。

Startup and code execution启动和代码执行

Upon startup with the -s option, IDLE will execute the file referenced by the environment variables IDLESTARTUP or PYTHONSTARTUP. IDLE first checks for IDLESTARTUP; if IDLESTARTUP is present the file referenced is run. If IDLESTARTUP is not present, IDLE checks for PYTHONSTARTUP. Files referenced by these environment variables are convenient places to store functions that are used frequently from the IDLE shell, or for executing import statements to import common modules.

In addition, Tk also loads a startup file if it is present. Note that the Tk file is loaded unconditionally. This additional file is .Idle.py and is looked for in the user’s home directory. Statements in this file will be executed in the Tk namespace, so this file is not useful for importing functions to be used from IDLE’s Python shell.该文件中的语句将在Tk命名空间中执行,因此该文件对于从IDLE的Python shell中导入要使用的函数没有用处。

Command line usage命令行用法

idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...
-c command run command in the shell window
-d enable debugger and open shell window
-e open editor window
-h print help message with legal combinations and exit
-i open shell window
-r file run file in shell window
-s run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
-t title set title of shell window
- run stdin in shell (- must be last option before args)

If there are arguments:如果有参数:

  • If -, -c, or r is used, all arguments are placed in sys.argv[1:...] and sys.argv[0] is set to '', '-c', or '-r'. 如果使用--cr,则所有参数都放在sys.argv[1:...]中,sys.argv[0]设置为'''-c''-r'No editor window is opened, even if that is the default set in the Options dialog.不会打开任何编辑器窗口,即使这是“选项”对话框中的默认设置。

  • Otherwise, arguments are files opened for editing and sys.argv reflects the arguments passed to IDLE itself.否则,参数是为编辑而打开的文件,sys.argv反映传递给IDLE本身的参数。

Startup failure启动失败

IDLE uses a socket to communicate between the IDLE GUI process and the user code execution process. IDLE使用套接字在空闲GUI进程和用户代码执行进程之间进行通信。A connection must be established whenever the Shell starts or restarts. 每当Shell启动或重新启动时,必须建立连接。(The latter is indicated by a divider line that says ‘RESTART’). (后者由表示“重启”的分隔线表示)。If the user process fails to connect to the GUI process, it usually displays a Tk error box with a ‘cannot connect’ message that directs the user here. 如果用户进程无法连接到GUI进程,它通常会显示一个Tk错误框,并显示一条“无法连接”消息,将用户引导到此处。It then exits.然后它退出。

One specific connection failure on Unix systems results from misconfigured masquerading rules somewhere in a system’s network setup. Unix系统上的一个特定连接故障是由于系统网络设置中某个地方配置错误的伪装规则造成的。When IDLE is started from a terminal, one will see a message starting with ** Invalid host:. 当从终端启动IDLE时,将看到一条以** Invalid host:开头的消息。The valid value is 127.0.0.1 (idlelib.rpc.LOCALHOST). 有效值是127.0.0.1 (idlelib.rpc.LOCALHOST)One can diagnose with tcpconnect -irv 127.0.0.1 6543 in one terminal window and tcplisten <same args> in another.可以在一个终端窗口中使用tcpconnect -irv 127.0.0.1 6543进行诊断,在另一个终端窗中使用tcplisten <same args>进行诊断。

A common cause of failure is a user-written file with the same name as a standard library module, such as random.py and tkinter.py. 常见的故障原因是用户编写的文件与标准库模块同名,如random.pytkinter.pyWhen such a file is located in the same directory as a file that is about to be run, IDLE cannot import the stdlib file. 当此类文件与即将运行的文件位于同一目录中时,IDLE无法导入stdlib文件。The current fix is to rename the user file.当前的修复方法是重命名用户文件。

Though less common than in the past, an antivirus or firewall program may stop the connection. 虽然不像过去那样常见,但防病毒或防火墙程序可能会停止连接。If the program cannot be taught to allow the connection, then it must be turned off for IDLE to work. 如果无法设定程序允许连接,则必须关闭该程序,以便空闲工作。It is safe to allow this internal connection because no data is visible on external ports. 允许这种内部连接是安全的,因为在外部端口上看不到任何数据。A similar problem is a network mis-configuration that blocks connections.类似的问题是阻止连接的网络错误配置。

Python installation issues occasionally stop IDLE: multiple versions can clash, or a single installation might need admin access. Python安装问题有时会停止空闲:多个版本可能会冲突,或者单个安装可能需要管理员访问。If one undo the clash, or cannot or does not want to run as admin, it might be easiest to completely remove Python and start over.如果有人撤销了冲突,或者不能或不想以管理员身份运行,那么完全删除Python并重新开始可能是最简单的。

A zombie pythonw.exe process could be a problem. 僵尸pythonwexe进程可能是一个问题。On Windows, use Task Manager to check for one and stop it if there is. 在Windows上,使用任务管理器检查一个任务,如果有则停止。Sometimes a restart initiated by a program crash or Keyboard Interrupt (control-C) may fail to connect. 有时,由程序崩溃或键盘中断(control-C)启动的重新启动可能无法连接。Dismissing the error box or using Restart Shell on the Shell menu may fix a temporary problem.关闭错误框或使用“外壳”菜单上的“重新启动外壳”可能会修复临时问题。

When IDLE first starts, it attempts to read user configuration files in ~/.idlerc/ (~ is one’s home directory). 当IDLE首次启动时,它尝试读取~/.idlerc/~是用户的主目录)中的用户配置文件。If there is a problem, an error message should be displayed. 如果出现问题,应显示错误消息。Leaving aside random disk glitches, this can be prevented by never editing the files by hand. 撇开随机磁盘故障不谈,这可以通过从不手动编辑文件来防止。Instead, use the configuration dialog, under Options. 相反,请使用“选项”下的“配置”对话框。Once there is an error in a user configuration file, the best solution may be to delete it and start over with the settings dialog.一旦用户配置文件中出现错误,最好的解决方案可能是将其删除,然后重新启动“设置”对话框。

If IDLE quits with no message, and it was not started from a console, try starting it from a console or terminal (python -m idlelib) and see if this results in an error message.如果IDLE退出时没有消息,并且它不是从控制台启动的,请尝试从控制台或终端(python-m idlelib)启动它,看看这是否会导致错误消息。

On Unix-based systems with tcl/tk older than 8.6.11 (see About IDLE) certain characters of certain fonts can cause a tk failure with a message to the terminal. 在基于Unix的系统上,tcl/tk早于8.6.11(请参见“关于IDLE”),某些字体的某些字符可能会导致tk故障,并向终端发送消息。This can happen either if one starts IDLE to edit a file with such a character or later when entering such a character. 如果开始空闲以编辑具有此字符的文件,或者稍后输入此字符时,可能会发生这种情况。If one cannot upgrade tcl/tk, then re-configure IDLE to use a font that works better.如果无法升级tcl/tk,则重新配置IDLE以使用效果更好的字体。

Running user code运行用户代码

With rare exceptions, the result of executing Python code with IDLE is intended to be the same as executing the same code by the default method, directly with Python in a text-mode system console or terminal window. 除了极少数例外,使用IDLE执行Python代码的结果与使用默认方法直接在文本模式系统控制台或终端窗口中使用Python执行相同代码的结果相同。However, the different interface and operation occasionally affect visible results. 但是,不同的界面和操作有时会影响可见结果。For instance, sys.modules starts with more entries, and threading.active_count() returns 2 instead of 1.例如,sysmodules从更多条目开始,threading.active_count()返回2而不是1。

By default, IDLE runs user code in a separate OS process rather than in the user interface process that runs the shell and editor. 默认情况下,IDLE在单独的操作系统进程中运行用户代码,而不是在运行shell和编辑器的用户界面进程中运行。In the execution process, it replaces sys.stdin, sys.stdout, and sys.stderr with objects that get input from and send output to the Shell window. The original values stored in sys.__stdin__, sys.__stdout__, and sys.__stderr__ are not touched, but may be None.

Sending print output from one process to a text widget in another is slower than printing to a system terminal in the same process. 将打印输出从一个进程发送到另一个进程中的文本小部件比在同一进程中打印到系统终端慢。This has the most effect when printing multiple arguments, as the string for each argument, each separator, the newline are sent separately. 这在打印多个参数时最有效,因为每个参数的字符串、每个分隔符和换行符都是单独发送的。For development, this is usually not a problem, but if one wants to print faster in IDLE, format and join together everything one wants displayed together and then print a single string. 对于开发来说,这通常不是问题,但如果希望在空闲时打印速度更快,请格式化并连接所有希望显示在一起的内容,然后打印单个字符串。Both format strings and str.join() can help combine fields and lines.格式字符串和str.join()都可以帮助组合字段和行。

IDLE’s standard stream replacements are not inherited by subprocesses created in the execution process, whether directly by user code or by modules such as multiprocessing. IDLE的标准流替换不会被执行过程中创建的子进程继承,无论是直接由用户代码还是由多处理等模块继承。If such subprocess use input from sys.stdin or print or write to sys.stdout or sys.stderr, IDLE should be started in a command line window. The secondary subprocess will then be attached to that window for input and output.

If sys is reset by user code, such as with importlib.reload(sys), IDLE’s changes are lost and input from the keyboard and output to the screen will not work correctly.

When Shell has the focus, it controls the keyboard and screen. 当Shell具有焦点时,它控制键盘和屏幕。This is normally transparent, but functions that directly access the keyboard and screen will not work. 这通常是透明的,但直接访问键盘和屏幕的功能将不起作用。These include system-specific functions that determine whether a key has been pressed and if so, which.这些功能包括特定于系统的功能,用于确定是否按下了某个键,如果是,则确定按下了哪个键。

The IDLE code running in the execution process adds frames to the call stack that would not be there otherwise. 在执行过程中运行的空闲代码将帧添加到调用堆栈中,否则这些帧将不存在。IDLE wraps sys.getrecursionlimit and sys.setrecursionlimit to reduce the effect of the additional stack frames.

When user code raises SystemExit either directly or by calling sys.exit, IDLE returns to a Shell prompt instead of exiting.当用户代码直接或通过调用sys.exit引发SystemExit时,IDLE将返回Shell提示而不是退出。

User output in ShellShell中的用户输出

When a program outputs text, the result is determined by the corresponding output device. 当程序输出文本时,结果由相应的输出设备确定。When IDLE executes user code, sys.stdout and sys.stderr are connected to the display area of IDLE’s Shell. 当IDLE执行用户代码时,sys.stdoutsys.stderr连接到IDLE外壳的显示区域。Some of its features are inherited from the underlying Tk Text widget. 它的一些特性是从底层Tk文本小部件继承的。Others are programmed additions. 其他是编程添加。Where it matters, Shell is designed for development rather than production runs.重要的是,壳牌是为开发而设计的,而不是为生产运行而设计的。

For instance, Shell never throws away output. 例如,Shell从不丢弃输出。A program that sends unlimited output to Shell will eventually fill memory, resulting in a memory error. 向Shell发送无限输出的程序最终会填满内存,导致内存错误。In contrast, some system text windows only keep the last n lines of output. 相反,一些系统文本窗口仅保留输出的最后n行。A Windows console, for instance, keeps a user-settable 1 to 9999 lines, with 300 the default.例如,Windows控制台将用户设置为1到9999行,默认为300行。

A Tk Text widget, and hence IDLE’s Shell, displays characters (codepoints) in the BMP (Basic Multilingual Plane) subset of Unicode. Tk文本小部件以及IDLE的Shell在Unicode的BMP(基本多语言平面)子集中显示字符(代码点)。Which characters are displayed with a proper glyph and which with a replacement box depends on the operating system and installed fonts. 哪些字符用适当的字形显示,哪些字符用替换框显示,这取决于操作系统和安装的字体。Tab characters cause the following text to begin after the next tab stop. 制表符字符导致以下文本在下一个制表符停止后开始。(They occur every 8 ‘characters’). (每8个字符出现一次)。Newline characters cause following text to appear on a new line. 换行符会导致以下文本出现在新行上。Other control characters are ignored or displayed as a space, box, or something else, depending on the operating system and font. 根据操作系统和字体,其他控制字符将被忽略或显示为空格、方框或其他形式。(Moving the text cursor through such output with arrow keys may exhibit some surprising spacing behavior.)(使用箭头键在输出中移动文本光标可能会表现出一些令人惊讶的间距行为。)

>>> s = 'a\tb\a<\x02><\r>\bc\nd'  # Enter 22 chars.
>>> len(s)
14
>>> s # Display repr(s)
'a\tb\x07<\x02><\r>\x08c\nd'
>>> print(s, end='') # Display s as is.
# Result varies by OS and font. Try it.

The repr function is used for interactive echo of expression values. repr函数用于表达式值的交互式回显。It returns an altered version of the input string in which control codes, some BMP codepoints, and all non-BMP codepoints are replaced with escape codes. 它返回输入字符串的更改版本,其中控制代码、一些BMP代码点和所有非BMP代码点将替换为转义代码。As demonstrated above, it allows one to identify the characters in a string, regardless of how they are displayed.如上所述,它允许识别字符串中的字符,而不管它们是如何显示的。

Normal and error output are generally kept separate (on separate lines) from code input and each other. They each get different highlight colors.正常和错误输出通常与代码输入和彼此保持分离(在单独的行上)。它们每个都有不同的高亮颜色。

For SyntaxError tracebacks, the normal ‘^’ marking where the error was detected is replaced by coloring the text with an error highlight. 对于SyntaxError回溯,检测到错误的正常“^”标记将替换为用错误高亮显示文本。When code run from a file causes other exceptions, one may right click on a traceback line to jump to the corresponding line in an IDLE editor. 当从文件运行的代码导致其他异常时,可以右键单击回溯行以跳转到空闲编辑器中的相应行。The file will be opened if necessary.如有必要,将打开该文件。

Shell has a special facility for squeezing output lines down to a ‘Squeezed text’ label. Shell有一种特殊的功能,可以将输出行压缩为“压缩文本”标签。This is done automatically for output over N lines (N = 50 by default). 这对于N行上的输出是自动完成的(默认情况下N=50)。N can be changed in the PyShell section of the General page of the Settings dialog. N可以在设置对话框的常规页面的PyShell部分中更改。Output with fewer lines can be squeezed by right clicking on the output. 通过右键单击输出,可以压缩行数较少的输出。This can be useful lines long enough to slow down scrolling.这可以是足够长的有用行,以减缓滚动。

Squeezed output is expanded in place by double-clicking the label. 通过双击标签,压缩输出就地展开。It can also be sent to the clipboard or a separate view window by right-clicking the label.也可以通过右键单击标签将其发送到剪贴板或单独的视图窗口。

Developing tkinter applications开发tkinter应用程序

IDLE is intentionally different from standard Python in order to facilitate development of tkinter programs. IDLE故意与标准Python不同,以便于tkinter程序的开发。Enter import tkinter as tk; root = tk.Tk() in standard Python and nothing appears. 在标准Python中输入import tkinter as tk; root = tk.Tk(),并且没有显示任何内容。Enter the same in IDLE and a tk window appears. 在IDLE中输入相同值,将显示tk窗口。In standard Python, one must also enter root.update() to see the window. 在标准Python中,还必须输入root.update()才能看到窗口。IDLE does the equivalent in the background, about 20 times a second, which is about every 50 milliseconds. IDLE在后台执行相同的操作,大约每秒20次,大约每50毫秒一次。Next enter b = tk.Button(root, text='button'); b.pack(). 接下来输入b = tk.Button(root, text='button'); b.pack()Again, nothing visibly changes in standard Python until one enters root.update().同样,在输入root.update()之前,标准Python中没有明显变化。

Most tkinter programs run root.mainloop(), which usually does not return until the tk app is destroyed. 大多数tkinter程序运行root.mainloop(),通常在tk应用程序被销毁之前不会返回。If the program is run with python -i or from an IDLE editor, a >>> shell prompt does not appear until mainloop() returns, at which time there is nothing left to interact with.如果程序是用python -i或从空闲编辑器运行的,则在mainloop()返回之前不会出现>>>shell提示,此时没有任何可与之交互的内容。

When running a tkinter program from an IDLE editor, one can comment out the mainloop call. 当从空闲编辑器运行tkinter程序时,可以注释掉主循环调用。One then gets a shell prompt immediately and can interact with the live application. 然后立即得到shell提示,并可以与实时应用程序交互。One just has to remember to re-enable the mainloop call when running in standard Python.在标准Python中运行时,只需记住重新启用mainloop调用。

Running without a subprocess无子进程运行

By default, IDLE executes user code in a separate subprocess via a socket, which uses the internal loopback interface. 默认情况下,IDLE通过使用内部环回接口的套接字在单独的子进程中执行用户代码。This connection is not externally visible and no data is sent to or received from the internet. 此连接在外部不可见,并且不会向internet发送数据或从internet接收数据。If firewall software complains anyway, you can ignore it.如果防火墙软件仍有投诉,您可以忽略它。

If the attempt to make the socket connection fails, Idle will notify you. 如果尝试建立套接字连接失败,Idle将通知您。Such failures are sometimes transient, but if persistent, the problem may be either a firewall blocking the connection or misconfiguration of a particular system. 此类故障有时是暂时的,但如果持续存在,问题可能是防火墙阻止连接或特定系统的配置错误。Until the problem is fixed, one can run Idle with the -n command line switch.在问题解决之前,可以使用-n命令行开关空闲运行。

If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. 如果使用-n命令行开关启动IDLE,它将在单个进程中运行,并且不会创建运行RPC Python执行服务器的子进程。This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. 如果Python无法在您的平台上创建子进程或RPC套接字接口,这将非常有用。However, in this mode user code is not isolated from IDLE itself. 然而,在这种模式下,用户代码不会与空闲本身隔离。Also, the environment is not restarted when Run/Run Module (F5) is selected. 此外,当选择运行/运行模块(F5)时,环境不会重新启动。If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. 如果您的代码已被修改,您必须reload()受影响的模块,并重新导入任何特定项(例如从foo import baz),如果更改要生效。For these reasons, it is preferable to run IDLE with the default subprocess if at all possible.由于这些原因,如果可能的话,最好使用默认子进程空闲运行。

Deprecated since version 3.4.从3.4版起已弃用。

Help and preferences帮助和偏好

Help sources帮助来源

Help menu entry “IDLE Help” displays a formatted html version of the IDLE chapter of the Library Reference. 帮助菜单条目“空闲帮助”显示库参考的空闲章节的格式化html版本。The result, in a read-only tkinter text window, is close to what one sees in a web browser. 结果,在只读tkinter文本窗口中,与web浏览器中的结果非常接近。Navigate through the text with a mousewheel, the scrollbar, or up and down arrow keys held down. 使用鼠标滚轮、滚动条或按住上下箭头键浏览文本。Or click the TOC (Table of Contents) button and select a section header in the opened box.或者单击TOC(目录)按钮,并在打开的框中选择节标题。

Help menu entry “Python Docs” opens the extensive sources of help, including tutorials, available at docs.python.org/x.y, where ‘x.y’ is the currently running Python version. 帮助菜单条目“Python文档”打开了大量的帮助源,包括教程,可从docs.python.org/x.y获得,其中“xy”是当前运行的Python版本。If your system has an off-line copy of the docs (this may be an installation option), that will be opened instead.如果您的系统有文档的脱机副本(这可能是一个安装选项),则会打开该副本。

Selected URLs can be added or removed from the help menu at any time using the General tab of the Configure IDLE dialog.可以随时使用“配置空闲”对话框的“常规”选项卡从“帮助”菜单中添加或删除选定的URL。

Setting preferences设置首选项

The font preferences, highlighting, keys, and general preferences can be changed via Configure IDLE on the Option menu. 可以通过选项菜单上的配置空闲来更改字体首选项、高亮显示、按键和常规首选项。Non-default user settings are saved in a .idlerc directory in the user’s home directory. 非默认用户设置保存在用户主目录中的idlerc目录中。Problems caused by bad user configuration files are solved by editing or deleting one or more of the files in .idlerc.通过编辑或删除.idlerc中的一个或多个文件,可以解决由错误用户配置文件引起的问题。

On the Font tab, see the text sample for the effect of font face and size on multiple characters in multiple languages. 在“字体”选项卡上,请参阅文本示例,了解字体和大小对多种语言中多个字符的影响。Edit the sample to add other characters of personal interest. 编辑示例以添加其他个人感兴趣的字符。Use the sample to select monospaced fonts. 使用此示例选择等距字体。If particular characters have problems in Shell or an editor, add them to the top of the sample and try changing first size and then font.如果特定字符在Shell或编辑器中有问题,请将其添加到示例的顶部,并尝试先更改大小,然后更改字体。

On the Highlights and Keys tab, select a built-in or custom color theme and key set. 在“高光和关键点”选项卡上,选择内置或自定义颜色主题和关键点集。To use a newer built-in color theme or key set with older IDLEs, save it as a new custom theme or key set and it well be accessible to older IDLEs.要将较新的内置颜色主题或键集与旧的IDLE一起使用,请将其另存为新的自定义主题或键集中,旧的IDL可以很好地访问它。

IDLE on macOS在macOS上空闲

Under System Preferences: Dock, one can set “Prefer tabs when opening documents” to “Always”. 在“系统首选项:停靠”下,可以将“打开文档时首选选项卡”设置为“始终”。This setting is not compatible with the tk/tkinter GUI framework used by IDLE, and it breaks a few IDLE features.此设置与IDLE使用的tk/tkinter GUI框架不兼容,并且它破坏了一些IDLE特性。

Extensions扩展

IDLE contains an extension facility. IDLE包含一个扩展设施。Preferences for extensions can be changed with the Extensions tab of the preferences dialog. 可以使用“首选项”对话框的“扩展”选项卡更改扩展的首选项。See the beginning of config-extensions.def in the idlelib directory for further information. 有关更多信息,请参阅idlelib目录中config-extensions.def的开头。The only current default extension is zzdummy, an example also used for testing.当前唯一的默认扩展是zzdummy,这也是一个用于测试的示例。