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 toolkittkinter
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配置、浏览器和其他对话框
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
, orr
is used, all arguments are placed insys.argv[1:...]
andsys.argv[0]
is set to''
,'-c'
, or'-r'
.-
、-c
或r
,则所有参数都放在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反映传递给IDLE本身的参数。sys.argv
reflects the arguments passed to IDLE itself.
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 如果用户进程无法连接到GUI进程,它通常会显示一个Tk
error box with a ‘cannot connect’ message that directs the user here. 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 当从终端启动IDLE时,将看到一条以** Invalid host:
. ** 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.py和tkinter.py。When 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 当IDLE首次启动时,它尝试读取~/.idlerc/
(~ is one’s home directory). ~/.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 (如果IDLE退出时没有消息,并且它不是从控制台启动的,请尝试从控制台或终端(python -m idlelib
) and see if this results in an error message.python-m idlelib
)启动它,看看这是否会导致错误消息。
On Unix-based systems with tcl/tk older than 在基于Unix的系统上,tcl/tk早于8.6.11
(see About IDLE
) certain characters of certain fonts can cause a tk failure with a message to the terminal. 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, 例如,sysmodules从更多条目开始,sys.modules
starts with more entries, and threading.active_count()
returns 2 instead of 1.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, 当IDLE执行用户代码时,sys.stdout
and sys.stderr
are connected to the display area of IDLE’s Shell. sys.stdout
和sys.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 在标准Python中输入import tkinter as tk; root = tk.Tk()
in standard Python and nothing appears. 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 在标准Python中,还必须输入root.update()
to see the window. 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 大多数tkinter程序运行root.mainloop()
, which usually does not return until the tk app is destroyed. 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 帮助菜单条目“Python文档”打开了大量的帮助源,包括教程,可从docs.python.org/x.y
, where ‘x.y’ is the currently running Python version. 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目录中。.idlerc
directory in the user’s home directory. 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,这也是一个用于测试的示例。