IDLE --- Python 編輯器與 shell¶
原始碼:Lib/idlelib/
IDLE 是 Python 的整合開發與學習環境 (Integrated Development and Learning Environment)。
IDLE 具有以下功能:
跨平台:在 Windows、Unix 和 macOS 上的運作大致相同
Python shell window(互動式直譯器)提供有色彩的程式碼輸入、輸出和錯誤訊息
多視窗文字編輯器,具有多次復原、Python 語法上色、智慧縮排、呼叫提示、自動完成等功能
能在任何視窗中搜尋、編輯器視窗中取代文字,以及搜尋多個檔案 (grep)
具有持久性斷點、能夠逐步執行和檢視全域和區域命名空間的除錯器
設定、瀏覽器和其他對話框
The IDLE application is implemented in the idlelib package.
This is an optional module. If it is missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you). If you are the distributor, see 可選模組的需求.
目錄¶
IDLE has two main window types, the Shell window and the Editor window. It is possible to have multiple editor windows simultaneously. On Windows and Linux, each has its own top menu. Each menu documented below indicates which window type it is associated with.
Output windows, such as used for Edit => Find in Files, are a subtype of editor window. They currently have the same top menu but a different default title and context menu.
On macOS, there is one application menu. It dynamically changes according to the window currently selected. It has an IDLE menu, and some entries described below are moved around to conform to Apple guidelines.
File menu (Shell and Editor)¶
- 新增檔案
Create a new file editing window.
- Open...
Open an existing file with an Open dialog.
- Open Module...
Open an existing module (searches sys.path).
- Recent Files
Open a list of recent files. Click one to open it.
- Module Browser
Show functions, classes, and methods in the current Editor file in a tree structure. In the shell, open a module first.
- Path Browser
Show sys.path directories, modules, functions, classes and methods in a tree structure.
- Save
Save the current window to the associated file, if there is one. Windows that have been changed since being opened or last saved have a * before and after the window title. If there is no associated file, do Save As instead.
- Save As...
Save the current window with a Save As dialog. The file saved becomes the new associated file for the window. (If your file manager is set to hide extensions, the current extension will be omitted in the file name box. If the new filename has no '.', '.py' and '.txt' will be added for Python and text files, except that on macOS Aqua,'.py' is added for all files.)
- Save Copy As...
Save the current window to different file without changing the associated file. (See Save As note above about filename extensions.)
- Print Window
Print the current window to the default printer.
- Close Window
Close the current window (if an unsaved editor, ask to save; if an unsaved Shell, ask to quit execution). Calling
exit()orclose()in the Shell window also closes Shell. If this is the only window, also exit IDLE.- 離開 IDLE
Close all windows and quit IDLE (ask to save unsaved edit windows).
Edit menu (Shell and Editor)¶
- Undo
Undo the last change to the current window. A maximum of 1000 changes may be undone.
- Redo
Redo the last undone change to the current window.
- Select All(選擇全部)
Select the entire contents of the current window.
- Cut(剪下)
Copy selection into the system-wide clipboard; then delete the selection.
- Copy(複製)
Copy selection into the system-wide clipboard.
- Paste(貼上)
Insert contents of the system-wide clipboard into the current window.
The clipboard functions are also available in context menus.
- Find...
Open a search dialog with many options
- Find Again
Repeat the last search, if there is one.
- Find Selection
Search for the currently selected string, if there is one.
- Find in Files...
Open a file search dialog. Put results in a new output window.
- Replace...
Open a search-and-replace dialog.
- Go to Line
Move the cursor to the beginning of the line requested and make that line visible. A request past the end of the file goes to the end. Clear any selection and update the line and column status.
- Show Completions
Open a scrollable list allowing selection of existing names. See Completions in the Editing and Navigation section below.
- Expand Word
Expand a prefix you have typed to match a full word in the same window; repeat to get a different expansion.
- Show Call Tip
After an unclosed parenthesis for a function, open a small window with function parameter hints. See Calltips in the Editing and Navigation section below.
- Show Surrounding Parens
Highlight the surrounding parenthesis.
Format menu (Editor window only)¶
- Format Paragraph
Rewrap the text block containing the text insert cursor. Avoid code lines. See Format block in the Editing and Navigation section below.
- Indent Region
Shift selected lines right by the indent width (default 4 spaces).
- Dedent Region
Shift selected lines left by the indent width (default 4 spaces).
- Comment Out Region
Insert ## in front of selected lines.
- Uncomment Region
Remove leading # or ## from selected lines.
- Tabify Region
Turn leading stretches of spaces into tabs. (Note: We recommend using 4 space blocks to indent Python code.)
- Untabify Region
Turn all tabs into the correct number of spaces.
- Toggle Tabs
Open a dialog to switch between indenting with spaces and tabs.
- New Indent Width
Open a dialog to change indent width. The accepted default by the Python community is 4 spaces.
- Strip Trailing Whitespace
Remove trailing space and other whitespace characters after the last non-whitespace character of a line by applying
str.rstrip()to each line, including lines within multiline strings. Except for Shell windows, remove extra newlines at the end of the file.
Run menu (Editor window only)¶
- Run Module
Do Check Module. If no error, restart the shell to clean the environment, then execute the module. Output is displayed in the Shell window. Note that output requires use of
printorwrite. When execution is complete, the Shell retains focus and displays a prompt. At this point, one may interactively explore the result of execution. This is similar to executing a file withpython -i fileat a command line.
- Run... Customized
Same as Run Module, but run the module with customized settings. Command Line Arguments extend
sys.argvas if passed on a command line. The module can be run in the Shell without restarting.
- Check Module
Check the syntax of the module currently open in the Editor window. If the module has not been saved IDLE will either prompt the user to save or autosave, as selected in the General tab of the Idle Settings dialog. If there is a syntax error, the approximate location is indicated in the Editor window.
- Python Shell
Open or wake up the Python Shell window.
Shell menu (Shell window only)¶
- View Last Restart
Scroll the shell window to the last Shell restart.
- Restart Shell
Restart the shell to clean the environment and reset display and exception handling.
- Previous History
Cycle through earlier commands in history which match the current entry.
- Next History
Cycle through later commands in history which match the current entry.
- Interrupt Execution
Stop a running program.
Debug menu (Shell window only)¶
- Go to File/Line
Look on the current line. with the cursor, and the line above for a filename and line number. If found, open the file if not already open, and show the line. Use this to view source lines referenced in an exception traceback and lines found by Find in Files. Also available in the context menu of the Shell window and Output windows.
- Debugger (toggle)
When activated, code entered in the Shell or run from an Editor will run under the debugger. In the Editor, breakpoints can be set with the context menu. This feature is still incomplete and somewhat experimental.
- Stack Viewer
Show the stack traceback of the last exception in a tree widget, with access to locals and globals.
- Auto-open Stack Viewer
Toggle automatically opening the stack viewer on an unhandled exception.
Options menu (Shell and Editor)¶
- Configure IDLE
Open a configuration dialog and change preferences for the following: fonts, indentation, keybindings, text color themes, startup windows and size, additional help sources, and extensions. On macOS, open the configuration dialog by selecting Preferences in the application menu. For more details, see Setting preferences under Help and preferences.
Most configuration options apply to all windows or all future windows. The option items below only apply to the active window.
- Show/Hide Code Context (Editor Window only)
Open a pane at the top of the edit window which shows the block context of the code which has scrolled above the top of the window. See Code Context in the Editing and Navigation section below.
- Show/Hide Line Numbers (Editor Window only)
Open a column to the left of the edit window which shows the number of each line of text. The default is off, which may be changed in the preferences (see Setting preferences).
- Zoom/Restore Height
Toggles the window between normal size and maximum height. The initial size defaults to 40 lines by 80 chars unless changed on the General tab of the Configure IDLE dialog. The maximum height for a screen is determined by momentarily maximizing a window the first time one is zoomed on the screen. Changing screen settings may invalidate the saved height. This toggle has no effect when a window is maximized.
Window menu (Shell and Editor)¶
Lists the names of all open windows; select one to bring it to the foreground (deiconifying it if necessary).
Help menu (Shell and Editor)¶
- 關於 IDLE
Display version, copyright, license, credits, and more.
- IDLE Help
Display this IDLE document, detailing the menu options, basic editing and navigation, and other tips.
- Python 文件
Access local Python documentation, if installed, or start a web browser and open docs.python.org showing the latest Python documentation.
- Turtle Demo
Run the turtledemo module with example Python code and turtle drawings.
Additional help sources may be added here with the Configure IDLE dialog under the General tab. See the Help sources subsection below for more on Help menu choices.
Context menus¶
Open a context menu by right-clicking in a window (Control-click on macOS). Context menus have the standard clipboard functions also on the Edit menu.
- Cut(剪下)
Copy selection into the system-wide clipboard; then delete the selection.
- Copy(複製)
Copy selection into the system-wide clipboard.
- Paste(貼上)
Insert contents of the system-wide clipboard into the current window.
Editor windows also have breakpoint functions. Lines with a breakpoint set are
specially marked. Breakpoints only have an effect when running under the
debugger. Breakpoints for a file are saved in the user's .idlerc
directory.
- Set Breakpoint
Set a breakpoint on the current line.
- Clear Breakpoint
Clear the breakpoint on that line.
Shell and Output windows also have the following.
- Go to file/line
Same as in Debug menu.
The Shell window also has an output squeezing facility explained in the Python Shell window subsection below.
- Squeeze
If the cursor is over an output line, squeeze all the output between the code above and the prompt below down to a 'Squeezed text' label.
Editing and Navigation¶
Editor windows¶
IDLE may open editor windows when it starts, depending on settings and how you start 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. The status bar contains the line number ('Ln') and column number ('Col'). Line numbers start with 1; column numbers with 0.
IDLE assumes that files with a known .py* extension contain Python code and that other files do not. Run Python code with the Run menu.
Key bindings¶
The IDLE insertion cursor is a thin vertical bar between character positions. When characters are entered, the insertion cursor and everything to its right moves right one character and the new character is entered in the new space.
Several non-character keys move the cursor and possibly delete characters. Deletion does not puts text on the clipboard, but IDLE has an undo list. Wherever this doc discusses keys, 'C' refers to the Control key on Windows and Unix and the Command key on macOS. (And all such discussions assume that the keys have not been re-bound to something else.)
Arrow keys move the cursor one character or line.
C-LeftArrow and C-RightArrow moves left or right one word.
Home and End go to the beginning or end of the line.
Page Up and Page Down go up or down one screen.
C-Home and C-End go to beginning or end of the file.
Backspace and Del (or C-d) delete the previous or next character.
C-Backspace and C-Del delete one word left or right.
C-k deletes ('kills') everything to the right.
Standard keybindings (like C-c to copy and C-v to paste) may work. 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). After certain keywords (break, return etc.) the next line is dedented. 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.
See also the indent/dedent region commands on the Format menu.
Search and Replace¶
Any selection becomes a search target. However, only selections within
a line work because searches are only performed within lines with the
terminal newline removed. If [x] Regular expression is checked, the
target is interpreted according to the Python re module.
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. (To prevent auto popups, set the delay to a
large number of milliseconds, such as 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. (On Windows,
one can specify a drive first.) 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. 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. (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.
For example, restart the Shell and enter itertools.count(. A calltip
appears because Idle imports itertools into the user process for its own
use. (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.
Format block¶
Reformat Paragraph rewraps a block ('paragraph') of contiguous equally indented non-blank comments, a similar block of text within a multiline string, or a selected subset of either. If needed, add a blank line to separate string from code. Partial lines in a selection expand to complete lines. The resulting lines have the same indent as before but have maximum total length of N columns (characters). Change the default N of 72 on the Window tab of IDLE Settings.
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. 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. 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). 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.
Shell window¶
In IDLE's Shell, enter, edit, and recall complete statements. (Most consoles and terminals only work with a single physical line at a time).
Submit a single-line statement for execution by hitting Return with the cursor anywhere on the line. If a line is extended with Backslash (\), the cursor must be on the last physical line. Submit a multi-line compound statement by entering a blank line after the statement.
When one pastes code into Shell, it is not compiled and possibly executed
until one hits Return, as specified above.
One may edit pasted code first.
If one pastes more than one statement into Shell, the result will be a
SyntaxError when multiple statements are compiled as if they were one.
Lines containing RESTART mean that the user execution process has been
re-started. This occurs when the user execution process has crashed,
when one requests a restart on the Shell menu, or when one runs code
in an editor window.
The editing features described in previous subsections work when entering code interactively. IDLE's Shell window also responds to the following:
C-c attempts to interrupt statement execution (but may fail).
C-d closes Shell if typed at a
>>>prompt.Alt-p and Alt-n (C-p and C-n on macOS) retrieve to the current prompt the previous or next previously entered statement that matches anything already typed.
Return while the cursor is on any previous statement appends the latter to anything already typed at the prompt.
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.
命令列用法¶
IDLE can be invoked from the command line with various options. The general syntax is:
python -m idlelib [options] [file ...]
The following options are available:
- -c <command>