Debian Codegraph @

Doc/library/idle.rst

raw
1 .. _idle:
2
3 IDLE --- Python editor and shell
4 ================================
5
6 .. moduleauthor:: Guido van Rossum <[email protected]>
7
8 **Source code:** :source:`Lib/idlelib/`
9
10 .. index::
11 single: IDLE
12 single: Python Editor
13 single: Integrated Development Environment
14
15 ..
16 Remember to update Lib/idlelib/help.html with idlelib.help.copy_strip() when modifying this file.
17
18 --------------
19
20 IDLE is Python's Integrated Development and Learning Environment.
21
22 IDLE has the following features:
23
24 * cross-platform: works mostly the same on Windows, Unix, and macOS
25
26 * Python shell window (interactive interpreter) with colorizing
27 of code input, output, and error messages
28
29 * multi-window text editor with multiple undo, Python colorizing,
30 smart indent, call tips, auto completion, and other features
31
32 * search within any window, replace within editor windows, and search
33 through multiple files (grep)
34
35 * debugger with persistent breakpoints, stepping, and viewing
36 of global and local namespaces
37
38 * configuration, browsers, and other dialogs
39
40 The IDLE application is implemented in the :mod:`idlelib` package.
41
42 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).
43 If you are the distributor, see Requirements for optional modules.
44
45 Menus
46 -----
47
48 IDLE has two main window types, the Shell window and the Editor window. It is
49 possible to have multiple editor windows simultaneously. On Windows and
50 Linux, each has its own top menu. Each menu documented below indicates
51 which window type it is associated with.
52
53 Output windows, such as used for Edit => Find in Files, are a subtype of editor
54 window. They currently have the same top menu but a different
55 default title and context menu.
56
57 On macOS, there is one application menu. It dynamically changes according
58 to the window currently selected. It has an IDLE menu, and some entries
59 described below are moved around to conform to Apple guidelines.
60
61 File menu (Shell and Editor)
62 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
63
64 New File
65 Create a new file editing window.
66
67 Open...
68 Open an existing file with an Open dialog.
69
70 Open Module...
71 Open an existing module (searches sys.path).
72
73 Recent Files
74 Open a list of recent files. Click one to open it.
75
76 .. index::
77 single: Module browser
78 single: Path browser
79
80 Module Browser
81 Show functions, classes, and methods in the current Editor file in a
82 tree structure. In the shell, open a module first.
83
84 Path Browser
85 Show sys.path directories, modules, functions, classes and methods in a
86 tree structure.
87
88 Save
89 Save the current window to the associated file, if there is one. Windows
90 that have been changed since being opened or last saved have a \* before
91 and after the window title. If there is no associated file,
92 do Save As instead.
93
94 Save As...
95 Save the current window with a Save As dialog. The file saved becomes the
96 new associated file for the window. (If your file manager is set to hide
97 extensions, the current extension will be omitted in the file name box.
98 If the new filename has no '.', '.py' and '.txt' will be added for Python
99 and text files, except that on macOS Aqua,'.py' is added for all files.)
100
101 Save Copy As...
102 Save the current window to different file without changing the associated
103 file. (See Save As note above about filename extensions.)
104
105 Print Window
106 Print the current window to the default printer.
107
108 Close Window
109 Close the current window (if an unsaved editor, ask to save; if an unsaved
110 Shell, ask to quit execution). Calling ``exit()`` or ``close()`` in the Shell
111 window also closes Shell. If this is the only window, also exit IDLE.
112
113 Exit IDLE
114 Close all windows and quit IDLE (ask to save unsaved edit windows).
115
116 Edit menu (Shell and Editor)
117 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
118
119 Undo
120 Undo the last change to the current window. A maximum of 1000 changes may
121 be undone.
122
123 Redo
124 Redo the last undone change to the current window.
125
126 Select All
127 Select the entire contents of the current window.
128
129 Cut
130 Copy selection into the system-wide clipboard; then delete the selection.
131
132 Copy
133 Copy selection into the system-wide clipboard.
134
135 Paste
136 Insert contents of the system-wide clipboard into the current window.
137
138 The clipboard functions are also available in context menus.
139
140 Find...
141 Open a search dialog with many options
142
143 Find Again
144 Repeat the last search, if there is one.
145
146 Find Selection
147 Search for the currently selected string, if there is one.
148
149 Find in Files...
150 Open a file search dialog. Put results in a new output window.
151
152 Replace...
153 Open a search-and-replace dialog.
154
155 Go to Line
156 Move the cursor to the beginning of the line requested and make that
157 line visible. A request past the end of the file goes to the end.
158 Clear any selection and update the line and column status.
159
160 Show Completions
161 Open a scrollable list allowing selection of existing names. See
162 :ref:`Completions <completions>` in the Editing and Navigation section below.
163
164 Expand Word
165 Expand a prefix you have typed to match a full word in the same window;
166 repeat to get a different expansion.
167
168 Show Call Tip
169 After an unclosed parenthesis for a function, open a small window with
170 function parameter hints. See :ref:`Calltips <calltips>` in the
171 Editing and Navigation section below.
172
173 Show Surrounding Parens
174 Highlight the surrounding parenthesis.
175
176 .. _format-menu:
177
178 Format menu (Editor window only)
179 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
180
181 Format Paragraph
182 Rewrap the text block containing the text insert cursor.
183 Avoid code lines. See :ref:`Format block<format-block>` in the
184 Editing and Navigation section below.
185
186 Indent Region
187 Shift selected lines right by the indent width (default 4 spaces).
188
189 Dedent Region
190 Shift selected lines left by the indent width (default 4 spaces).
191
192 Comment Out Region
193 Insert ## in front of selected lines.
194
195 Uncomment Region
196 Remove leading # or ## from selected lines.
197
198 Tabify Region
199 Turn *leading* stretches of spaces into tabs. (Note: We recommend using
200 4 space blocks to indent Python code.)
201
202 Untabify Region
203 Turn *all* tabs into the correct number of spaces.
204
205 Toggle Tabs
206 Open a dialog to switch between indenting with spaces and tabs.
207
208 New Indent Width
209 Open a dialog to change indent width. The accepted default by the Python
210 community is 4 spaces.
211
212 Strip Trailing Whitespace
213 Remove trailing space and other whitespace characters after the last
214 non-whitespace character of a line by applying :meth:`str.rstrip` to each line,
215 including lines within multiline strings. Except for Shell windows,
216 remove extra newlines at the end of the file.
217
218 .. index::
219 single: Run script
220
221 Run menu (Editor window only)
222 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
223
224 .. _run-module:
225
226 Run Module
227 Do :ref:`Check Module <check-module>`. If no error, restart the shell to clean the
228 environment, then execute the module. Output is displayed in the Shell
229 window. Note that output requires use of ``print`` or ``write``.
230 When execution is complete, the Shell retains focus and displays a prompt.
231 At this point, one may interactively explore the result of execution.
232 This is similar to executing a file with ``python -i file`` at a command
233 line.
234
235 .. _run-custom:
236
237 Run... Customized
238 Same as :ref:`Run Module <run-module>`, but run the module with customized
239 settings. *Command Line Arguments* extend :data:`sys.argv` as if passed
240 on a command line. The module can be run in the Shell without restarting.
241
242 .. _check-module:
243
244 Check Module
245 Check the syntax of the module currently open in the Editor window. If the
246 module has not been saved IDLE will either prompt the user to save or
247 autosave, as selected in the General tab of the Idle Settings dialog. If
248 there is a syntax error, the approximate location is indicated in the
249 Editor window.
250
251 .. _python-shell:
252
253 Python Shell
254 Open or wake up the Python Shell window.
255
256
257 Shell menu (Shell window only)
258 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
259
260 View Last Restart
261 Scroll the shell window to the last Shell restart.
262
263 Restart Shell
264 Restart the shell to clean the environment and reset display and exception handling.
265
266 Previous History
267 Cycle through earlier commands in history which match the current entry.
268
269 Next History
270 Cycle through later commands in history which match the current entry.
271
272 Interrupt Execution
273 Stop a running program.
274
275 Debug menu (Shell window only)
276 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
277
278 Go to File/Line
279 Look on the current line. with the cursor, and the line above for a filename
280 and line number. If found, open the file if not already open, and show the
281 line. Use this to view source lines referenced in an exception traceback
282 and lines found by Find in Files. Also available in the context menu of
283 the Shell window and Output windows.
284
285 .. index::
286 single: debugger
287 single: stack viewer
288
289 Debugger (toggle)
290 When activated, code entered in the Shell or run from an Editor will run
291 under the debugger. In the Editor, breakpoints can be set with the context
292 menu. This feature is still incomplete and somewhat experimental.
293
294 Stack Viewer
295 Show the stack traceback of the last exception in a tree widget, with
296 access to locals and globals.
297
298 Auto-open Stack Viewer
299 Toggle automatically opening the stack viewer on an unhandled exception.
300
301 Options menu (Shell and Editor)
302 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
303
304 Configure IDLE
305 Open a configuration dialog and change preferences for the following:
306 fonts, indentation, keybindings, text color themes, startup windows and
307 size, additional help sources, and extensions. On macOS, open the
308 configuration dialog by selecting Preferences in the application
309 menu. For more details, see
310 :ref:`Setting preferences <preferences>` under Help and preferences.
311
312 Most configuration options apply to all windows or all future windows.
313 The option items below only apply to the active window.
314
315 Show/Hide Code Context (Editor Window only)
316 Open a pane at the top of the edit window which shows the block context
317 of the code which has scrolled above the top of the window. See
318 :ref:`Code Context <code-context>` in the Editing and Navigation section
319 below.
320
321 Show/Hide Line Numbers (Editor Window only)
322 Open a column to the left of the edit window which shows the number
323 of each line of text. The default is off, which may be changed in the
324 preferences (see :ref:`Setting preferences <preferences>`).
325
326 Zoom/Restore Height
327 Toggles the window between normal size and maximum height. The initial size
328 defaults to 40 lines by 80 chars unless changed on the General tab of the
329 Configure IDLE dialog. The maximum height for a screen is determined by
330 momentarily maximizing a window the first time one is zoomed on the screen.
331 Changing screen settings may invalidate the saved height. This toggle has
332 no effect when a window is maximized.
333
334 Window menu (Shell and Editor)
335 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
336
337 Lists the names of all open windows; select one to bring it to the foreground
338 (deiconifying it if necessary).
339
340 Help menu (Shell and Editor)
341 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
342
343 About IDLE
344 Display version, copyright, license, credits, and more.
345
346 IDLE Help
347 Display this IDLE document, detailing the menu options, basic editing and
348 navigation, and other tips.
349
350 Python Docs
351 Access local Python documentation, if installed, or start a web browser
352 and open docs.python.org showing the latest Python documentation.
353
354 Turtle Demo
355 Run the turtledemo module with example Python code and turtle drawings.
356
357 Additional help sources may be added here with the Configure IDLE dialog under
358 the General tab. See the :ref:`Help sources <help-sources>` subsection below
359 for more on Help menu choices.
360
361 .. index::
362 single: Cut
363 single: Copy
364 single: Paste
365 single: Set Breakpoint
366 single: Clear Breakpoint
367 single: breakpoints
368
369 Context menus
370 ^^^^^^^^^^^^^^^^^^^^^^^^^^
371
372 Open a context menu by right-clicking in a window (Control-click on macOS).
373 Context menus have the standard clipboard functions also on the Edit menu.
374
375 Cut
376 Copy selection into the system-wide clipboard; then delete the selection.
377
378 Copy
379 Copy selection into the system-wide clipboard.
380
381 Paste
382 Insert contents of the system-wide clipboard into the current window.
383
384 Editor windows also have breakpoint functions. Lines with a breakpoint set are
385 specially marked. Breakpoints only have an effect when running under the
386 debugger. Breakpoints for a file are saved in the user's ``.idlerc``
387 directory.
388
389 Set Breakpoint
390 Set a breakpoint on the current line.
391
392 Clear Breakpoint
393 Clear the breakpoint on that line.
394
395 Shell and Output windows also have the following.
396
397 Go to file/line
398 Same as in Debug menu.
399
400 The Shell window also has an output squeezing facility explained in the *Python
401 Shell window* subsection below.
402
403 Squeeze
404 If the cursor is over an output line, squeeze all the output between
405 the code above and the prompt below down to a 'Squeezed text' label.
406
407
408 .. _editing-and-navigation:
409
410 Editing and Navigation
411 ----------------------
412
413 Editor windows
414 ^^^^^^^^^^^^^^
415
416 IDLE may open editor windows when it starts, depending on settings
417 and how you start IDLE. Thereafter, use the File menu. There can be only
418 one open editor window for a given file.
419
420 The title bar contains the name of the file, the full path, and the version
421 of Python and IDLE running the window. The status bar contains the line
422 number ('Ln') and column number ('Col'). Line numbers start with 1;
423 column numbers with 0.
424
425 IDLE assumes that files with a known .py* extension contain Python code
426 and that other files do not. Run Python code with the Run menu.
427
428 Key bindings
429 ^^^^^^^^^^^^
430
431 The IDLE insertion cursor is a thin vertical bar between character
432 positions. When characters are entered, the insertion cursor and
433 everything to its right moves right one character and
434 the new character is entered in the new space.
435
436 Several non-character keys move the cursor and possibly
437 delete characters. Deletion does not puts text on the clipboard,
438 but IDLE has an undo list. Wherever this doc discusses keys,
439 'C' refers to the :kbd:`Control` key on Windows and
440 Unix and the :kbd:`Command` key on macOS. (And all such discussions
441 assume that the keys have not been re-bound to something else.)
442
443 * Arrow keys move the cursor one character or line.
444
445 * :kbd:`C-LeftArrow` and :kbd:`C-RightArrow` moves left or right one word.
446
447 * :kbd:`Home` and :kbd:`End` go to the beginning or end of the line.
448
449 * :kbd:`Page Up` and :kbd:`Page Down` go up or down one screen.
450
451 * :kbd:`C-Home` and :kbd:`C-End` go to beginning or end of the file.
452
453 * :kbd:`Backspace` and :kbd:`Del` (or :kbd:`C-d`) delete the previous
454 or next character.
455
456 * :kbd:`C-Backspace` and :kbd:`C-Del` delete one word left or right.
457
458 * :kbd:`C-k` deletes ('kills') everything to the right.
459
460 Standard keybindings (like :kbd:`C-c` to copy and :kbd:`C-v` to paste)
461 may work. Keybindings are selected in the Configure IDLE dialog.
462
463 Automatic indentation
464 ^^^^^^^^^^^^^^^^^^^^^
465
466 After a block-opening statement, the next line is indented by 4 spaces (in the
467 Python Shell window by one tab). After certain keywords (break, return etc.)
468 the next line is dedented. In leading indentation, :kbd:`Backspace` deletes up
469 to 4 spaces if they are there. :kbd:`Tab` inserts spaces (in the Python
470 Shell window one tab), number depends on Indent width. Currently, tabs
471 are restricted to four spaces due to Tcl/Tk limitations.
472
473 See also the indent/dedent region commands on the
474 :ref:`Format menu <format-menu>`.
475
476 Search and Replace
477 ^^^^^^^^^^^^^^^^^^
478
479 Any selection becomes a search target. However, only selections within
480 a line work because searches are only performed within lines with the
481 terminal newline removed. If ``[x] Regular expression`` is checked, the
482 target is interpreted according to the Python re module.
483
484 .. _completions:
485
486 Completions
487 ^^^^^^^^^^^
488
489 Completions are supplied, when requested and available, for module
490 names, attributes of classes or functions, or filenames. Each request
491 method displays a completion box with existing names. (See tab
492 completions below for an exception.) For any box, change the name
493 being completed and the item highlighted in the box by
494 typing and deleting characters; by hitting :kbd:`Up`, :kbd:`Down`,
495 :kbd:`PageUp`, :kbd:`PageDown`, :kbd:`Home`, and :kbd:`End` keys;
496 and by a single click within the box. Close the box with :kbd:`Escape`,
497 :kbd:`Enter`, and double :kbd:`Tab` keys or clicks outside the box.
498 A double click within the box selects and closes.
499
500 One way to open a box is to type a key character and wait for a
501 predefined interval. This defaults to 2 seconds; customize it
502 in the settings dialog. (To prevent auto popups, set the delay to a
503 large number of milliseconds, such as 100000000.) For imported module
504 names or class or function attributes, type '.'.
505 For filenames in the root directory, type :data:`os.sep` or
506 :data:`os.altsep` immediately after an opening quote. (On Windows,
507 one can specify a drive first.) Move into subdirectories by typing a
508 directory name and a separator.
509
510 Instead of waiting, or after a box is closed, open a completion box
511 immediately with Show Completions on the Edit menu. The default hot
512 key is :kbd:`C-space`. If one types a prefix for the desired name
513 before opening the box, the first match or near miss is made visible.
514 The result is the same as if one enters a prefix
515 after the box is displayed. Show Completions after a quote completes
516 filenames in the current directory instead of a root directory.
517
518 Hitting :kbd:`Tab` after a prefix usually has the same effect as Show
519 Completions. (With no prefix, it indents.) However, if there is only
520 one match to the prefix, that match is immediately added to the editor
521 text without opening a box.
522
523 Invoking 'Show Completions', or hitting :kbd:`Tab` after a prefix,
524 outside of a string and without a preceding '.' opens a box with
525 keywords, builtin names, and available module-level names.
526
527 When editing code in an editor (as oppose to Shell), increase the
528 available module-level names by running your code
529 and not restarting the Shell thereafter. This is especially useful
530 after adding imports at the top of a file. This also increases
531 possible attribute completions.
532
533 Completion boxes initially exclude names beginning with '_' or, for
534 modules, not included in '__all__'. The hidden names can be accessed
535 by typing '_' after '.', either before or after the box is opened.
536
537 .. _calltips:
538
539 Calltips
540 ^^^^^^^^
541
542 A calltip is shown automatically when one types :kbd:`(` after the name
543 of an *accessible* function. A function name expression may include
544 dots and subscripts. A calltip remains until it is clicked, the cursor
545 is moved out of the argument area, or :kbd:`)` is typed. Whenever the
546 cursor is in the argument part of a definition, select Edit and "Show
547 Call Tip" on the menu or enter its shortcut to display a calltip.
548
549 The calltip consists of the function's signature and docstring up to
550 the latter's first blank line or the fifth non-blank line. (Some builtin
551 functions lack an accessible signature.) A '/' or '*' in the signature
552 indicates that the preceding or following arguments are passed by
553 position or name (keyword) only. Details are subject to change.
554
555 In Shell, the accessible functions depends on what modules have been
556 imported into the user process, including those imported by Idle itself,
557 and which definitions have been run, all since the last restart.
558
559 For example, restart the Shell and enter ``itertools.count(``. A calltip
560 appears because Idle imports itertools into the user process for its own
561 use. (This could change.) Enter ``turtle.write(`` and nothing appears.
562 Idle does not itself import turtle. The menu entry and shortcut also do
563 nothing. Enter ``import turtle``. Thereafter, ``turtle.write(``
564 will display a calltip.
565
566 In an editor, import statements have no effect until one runs the file.
567 One might want to run a file after writing import statements, after
568 adding function definitions, or after opening an existing file.
569
570 .. _format-block:
571
572 Format block
573 ^^^^^^^^^^^^
574
575 Reformat Paragraph rewraps a block ('paragraph') of contiguous equally
576 indented non-blank comments, a similar block of text within a multiline
577 string, or a selected subset of either.
578 If needed, add a blank line to separate string from code.
579 Partial lines in a selection expand to complete lines.
580 The resulting lines have the same indent as before
581 but have maximum total length of N columns (characters).
582 Change the default N of 72 on the Window tab of IDLE Settings.
583
584 .. _code-context:
585
586 Code Context
587 ^^^^^^^^^^^^
588
589 Within an editor window containing Python code, code context can be toggled
590 in order to show or hide a pane at the top of the window. When shown, this
591 pane freezes the opening lines for block code, such as those beginning with
592 ``class``, ``def``, or ``if`` keywords, that would have otherwise scrolled
593 out of view. The size of the pane will be expanded and contracted as needed
594 to show the all current levels of context, up to the maximum number of
595 lines defined in the Configure IDLE dialog (which defaults to 15). If there
596 are no current context lines and the feature is toggled on, a single blank
597 line will display. Clicking on a line in the context pane will move that
598 line to the top of the editor.
599
600 The text and background colors for the context pane can be configured under
601 the Highlights tab in the Configure IDLE dialog.
602
603 Shell window
604 ^^^^^^^^^^^^
605
606 In IDLE's Shell, enter, edit, and recall complete statements. (Most
607 consoles and terminals only work with a single physical line at a time).
608
609 Submit a single-line statement for execution by hitting :kbd:`Return`
610 with the cursor anywhere on the line. If a line is extended with
611 Backslash (:kbd:`\\`), the cursor must be on the last physical line.
612 Submit a multi-line compound statement by entering a blank line after
613 the statement.
614
615 When one pastes code into Shell, it is not compiled and possibly executed
616 until one hits :kbd:`Return`, as specified above.
617 One may edit pasted code first.
618 If one pastes more than one statement into Shell, the result will be a
619 :exc:`SyntaxError` when multiple statements are compiled as if they were one.
620
621 Lines containing ``RESTART`` mean that the user execution process has been
622 re-started. This occurs when the user execution process has crashed,
623 when one requests a restart on the Shell menu, or when one runs code
624 in an editor window.
625
626 The editing features described in previous subsections work when entering
627 code interactively. IDLE's Shell window also responds to the following:
628
629 * :kbd:`C-c` attempts to interrupt statement execution (but may fail).
630
631 * :kbd:`C-d` closes Shell if typed at a ``>>>`` prompt.
632
633 * :kbd:`Alt-p` and :kbd:`Alt-n` (:kbd:`C-p` and :kbd:`C-n` on macOS)
634 retrieve to the current prompt the previous or next previously
635 entered statement that matches anything already typed.
636
637 * :kbd:`Return` while the cursor is on any previous statement
638 appends the latter to anything already typed at the prompt.
639
640 Text colors
641 ^^^^^^^^^^^
642
643 Idle defaults to black on white text, but colors text with special meanings.
644 For the shell, these are shell output, shell error, user output, and
645 user error. For Python code, at the shell prompt or in an editor, these are
646 keywords, builtin class and function names, names following ``class`` and
647 ``def``, strings, and comments. For any text window, these are the cursor (when
648 present), found text (when possible), and selected text.
649
650 IDLE also highlights the :ref:`soft keywords <soft-keywords>` :keyword:`match`,
651 :keyword:`case <match>`, and :keyword:`_ <wildcard-patterns>` in
652 pattern-matching statements. However, this highlighting is not perfect and
653 will be incorrect in some rare cases, including some ``_``-s in ``case``
654 patterns.
655
656 Text coloring is done in the background, so uncolorized text is occasionally
657 visible. To change the color scheme, use the Configure IDLE dialog
658 Highlighting tab. The marking of debugger breakpoint lines in the editor and
659 text in popups and dialogs is not user-configurable.
660
661
662 Startup and Code Execution
663 --------------------------
664
665 Upon startup with the ``-s`` option, IDLE will execute the file referenced by
666 the environment variables :envvar:`IDLESTARTUP` or :envvar:`PYTHONSTARTUP`.
667 IDLE first checks for ``IDLESTARTUP``; if ``IDLESTARTUP`` is present the file
668 referenced is run. If ``IDLESTARTUP`` is not present, IDLE checks for
669 ``PYTHONSTARTUP``. Files referenced by these environment variables are
670 convenient places to store functions that are used frequently from the IDLE
671 shell, or for executing import statements to import common modules.
672
673 In addition, ``Tk`` also loads a startup file if it is present. Note that the
674 Tk file is loaded unconditionally. This additional file is ``.Idle.py`` and is
675 looked for in the user's home directory. Statements in this file will be
676 executed in the Tk namespace, so this file is not useful for importing
677 functions to be used from IDLE's Python shell.
678
679 .. _idlelib-cli:
680
681 Command-line usage
682 ^^^^^^^^^^^^^^^^^^
683
684 .. program:: idle
685
686 IDLE can be invoked from the command line with various options. The general syntax is:
687
688 .. code-block:: bash
689
690 python -m idlelib [options] [file ...]
691
692 The following options are available:
693
694 .. option:: -c <command>
695
696 Run the specified Python command in the shell window.
697 For example, pass ``-c "print('Hello, World!')"``.
698 On Windows, the outer quotes must be double quotes as shown.
699
700 .. option:: -d
701
702 Enable the debugger and open the shell window.
703
704 .. option:: -e
705
706 Open an editor window.
707
708 .. option:: -h
709
710 Print a help message with legal combinations of options and exit.
711
712 .. option:: -i
713
714 Open a shell window.
715
716 .. option:: -r <file>
717
718 Run the specified file in the shell window.
719
720 .. option:: -s
721
722 Run the startup file (as defined by the environment variables :envvar:`IDLESTARTUP` or :envvar:`PYTHONSTARTUP`) before opening the shell window.
723
724 .. option:: -t <title>
725
726 Set the title of the shell window.
727
728 .. option:: -
729
730 Read and execute standard input in the shell window. This option must be the last one before any arguments.
731
732 If arguments are provided:
733
734 - If ``-``, ``-c``, or ``-r`` is used, all arguments are placed in ``sys.argv[1:]``,
735 and ``sys.argv[0]`` is set to ``''``, ``'-c'``, or ``'-r'`` respectively.
736 No editor window is opened, even if that is the default set in the *Options* dialog.
737 - Otherwise, arguments are treated as files to be opened for editing, and ``sys.argv`` reflects the arguments passed to IDLE itself.
738
739
740 Startup failure
741 ^^^^^^^^^^^^^^^
742
743 IDLE uses a socket to communicate between the IDLE GUI process and the user
744 code execution process. A connection must be established whenever the Shell
745 starts or restarts. (The latter is indicated by a divider line that says
746 'RESTART'). If the user process fails to connect to the GUI process, it
747 usually displays a ``Tk`` error box with a 'cannot connect' message
748 that directs the user here. It then exits.
749
750 One specific connection failure on Unix systems results from
751 misconfigured masquerading rules somewhere in a system's network setup.
752 When IDLE is started from a terminal, one will see a message starting
753 with ``** Invalid host:``.
754 The valid value is ``127.0.0.1 (idlelib.rpc.LOCALHOST)``.
755 One can diagnose with ``tcpconnect -irv 127.0.0.1 6543`` in one
756 terminal window and ``tcplisten <same args>`` in another.
757
758 A common cause of failure is a user-written file with the same name as a
759 standard library module, such as *random.py* and *tkinter.py*. When such a
760 file is located in the same directory as a file that is about to be run,
761 IDLE cannot import the stdlib file. The current fix is to rename the
762 user file.
763
764 Though less common than in the past, an antivirus or firewall program may
765 stop the connection. If the program cannot be taught to allow the
766 connection, then it must be turned off for IDLE to work. It is safe to
767 allow this internal connection because no data is visible on external
768 ports. A similar problem is a network mis-configuration that blocks
769 connections.
770
771 Python installation issues occasionally stop IDLE: multiple versions can
772 clash, or a single installation might need admin access. If one undo the
773 clash, or cannot or does not want to run as admin, it might be easiest to
774 completely remove Python and start over.
775
776 A zombie pythonw.exe process could be a problem. On Windows, use Task
777 Manager to check for one and stop it if there is. Sometimes a restart
778 initiated by a program crash or Keyboard Interrupt (control-C) may fail
779 to connect. Dismissing the error box or using Restart Shell on the Shell
780 menu may fix a temporary problem.
781
782 When IDLE first starts, it attempts to read user configuration files in
783 ``~/.idlerc/`` (~ is one's home directory). If there is a problem, an error
784 message should be displayed. Leaving aside random disk glitches, this can
785 be prevented by never editing the files by hand. Instead, use the
786 configuration dialog, under Options. Once there is an error in a user
787 configuration file, the best solution may be to delete it and start over
788 with the settings dialog.
789
790 If IDLE quits with no message, and it was not started from a console, try
791 starting it from a console or terminal (``python -m idlelib``) and see if
792 this results in an error message.
793
794 On Unix-based systems with tcl/tk older than ``8.6.11`` (see
795 ``About IDLE``) certain characters of certain fonts can cause
796 a tk failure with a message to the terminal. This can happen either
797 if one starts IDLE to edit a file with such a character or later
798 when entering such a character. If one cannot upgrade tcl/tk,
799 then re-configure IDLE to use a font that works better.
800
801 Running user code
802 ^^^^^^^^^^^^^^^^^
803
804 With rare exceptions, the result of executing Python code with IDLE is
805 intended to be the same as executing the same code by the default method,
806 directly with Python in a text-mode system console or terminal window.
807 However, the different interface and operation occasionally affect
808 visible results. For instance, ``sys.modules`` starts with more entries,
809 and ``threading.active_count()`` returns 2 instead of 1.
810
811 By default, IDLE runs user code in a separate OS process rather than in
812 the user interface process that runs the shell and editor. In the execution
813 process, it replaces ``sys.stdin``, ``sys.stdout``, and ``sys.stderr``
814 with objects that get input from and send output to the Shell window.
815 The original values stored in ``sys.__stdin__``, ``sys.__stdout__``, and
816 ``sys.__stderr__`` are not touched, but may be ``None``.
817
818 Sending print output from one process to a text widget in another is
819 slower than printing to a system terminal in the same process.
820 This has the most effect when printing multiple arguments, as the string
821 for each argument, each separator, the newline are sent separately.
822 For development, this is usually not a problem, but if one wants to
823 print faster in IDLE, format and join together everything one wants
824 displayed together and then print a single string. Both format strings
825 and :meth:`str.join` can help combine fields and lines.
826
827 IDLE's standard stream replacements are not inherited by subprocesses
828 created in the execution process, whether directly by user code or by
829 modules such as multiprocessing. If such subprocess use ``input`` from
830 sys.stdin or ``print`` or ``write`` to sys.stdout or sys.stderr,
831 IDLE should be started in a command line window. (On Windows,
832 use ``python`` or ``py`` rather than ``pythonw`` or ``pyw``.)
833 The secondary subprocess
834 will then be attached to that window for input and output.
835
836 If ``sys`` is reset by user code, such as with ``importlib.reload(sys)``,
837 IDLE's changes are lost and input from the keyboard and output to the screen
838 will not work correctly.
839
840 When Shell has the focus, it controls the keyboard and screen. This is
841 normally transparent, but functions that directly access the keyboard
842 and screen will not work. These include system-specific functions that
843 determine whether a key has been pressed and if so, which.
844
845 The IDLE code running in the execution process adds frames to the call stack
846 that would not be there otherwise. IDLE wraps ``sys.getrecursionlimit`` and
847 ``sys.setrecursionlimit`` to reduce the effect of the additional stack
848 frames.
849
850 When user code raises SystemExit either directly or by calling sys.exit,
851 IDLE returns to a Shell prompt instead of exiting.
852
853 User output in Shell
854 ^^^^^^^^^^^^^^^^^^^^
855
856 When a program outputs text, the result is determined by the
857 corresponding output device. When IDLE executes user code, ``sys.stdout``
858 and ``sys.stderr`` are connected to the display area of IDLE's Shell. Some of
859 its features are inherited from the underlying Tk Text widget. Others
860 are programmed additions. Where it matters, Shell is designed for development
861 rather than production runs.
862
863 For instance, Shell never throws away output. A program that sends unlimited
864 output to Shell will eventually fill memory, resulting in a memory error.
865 In contrast, some system text windows only keep the last n lines of output.
866 A Windows console, for instance, keeps a user-settable 1 to 9999 lines,
867 with 300 the default.
868
869 A Tk Text widget, and hence IDLE's Shell, displays characters (codepoints) in
870 the BMP (Basic Multilingual Plane) subset of Unicode. Which characters are
871 displayed with a proper glyph and which with a replacement box depends on the
872 operating system and installed fonts. Tab characters cause the following text
873 to begin after the next tab stop. (They occur every 8 'characters'). Newline
874 characters cause following text to appear on a new line. Other control
875 characters are ignored or displayed as a space, box, or something else,
876 depending on the operating system and font. (Moving the text cursor through
877 such output with arrow keys may exhibit some surprising spacing behavior.) ::
878
879 >>> s = 'a\tb\a<\x02><\r>\bc\nd' # Enter 22 chars.
880 >>> len(s)
881 14
882 >>> s # Display repr(s)
883 'a\tb\x07<\x02><\r>\x08c\nd'
884 >>> print(s, end='') # Display s as is.
885 # Result varies by OS and font. Try it.
886
887 The ``repr`` function is used for interactive echo of expression
888 values. It returns an altered version of the input string in which
889 control codes, some BMP codepoints, and all non-BMP codepoints are
890 replaced with escape codes. As demonstrated above, it allows one to
891 identify the characters in a string, regardless of how they are displayed.
892
893 Normal and error output are generally kept separate (on separate lines)
894 from code input and each other. They each get different highlight colors.
895
896 For SyntaxError tracebacks, the normal '^' marking where the error was
897 detected is replaced by coloring the text with an error highlight.
898 When code run from a file causes other exceptions, one may right click
899 on a traceback line to jump to the corresponding line in an IDLE editor.
900 The file will be opened if necessary.
901
902 Shell has a special facility for squeezing output lines down to a
903 'Squeezed text' label. This is done automatically
904 for output over N lines (N = 50 by default).
905 N can be changed in the PyShell section of the General
906 page of the Settings dialog. Output with fewer lines can be squeezed by
907 right clicking on the output. This can be useful lines long enough to slow
908 down scrolling.
909
910 Squeezed output is expanded in place by double-clicking the label.
911 It can also be sent to the clipboard or a separate view window by
912 right-clicking the label.
913
914 Developing tkinter applications
915 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
916
917 IDLE is intentionally different from standard Python in order to
918 facilitate development of tkinter programs. Enter ``import tkinter as tk;
919 root = tk.Tk()`` in standard Python and nothing appears. Enter the same
920 in IDLE and a tk window appears. In standard Python, one must also enter
921 ``root.update()`` to see the window. IDLE does the equivalent in the
922 background, about 20 times a second, which is about every 50 milliseconds.
923 Next enter ``b = tk.Button(root, text='button'); b.pack()``. Again,
924 nothing visibly changes in standard Python until one enters ``root.update()``.
925
926 Most tkinter programs run ``root.mainloop()``, which usually does not
927 return until the tk app is destroyed. If the program is run with
928 ``python -i`` or from an IDLE editor, a ``>>>`` shell prompt does not
929 appear until ``mainloop()`` returns, at which time there is nothing left
930 to interact with.
931
932 When running a tkinter program from an IDLE editor, one can comment out
933 the mainloop call. One then gets a shell prompt immediately and can
934 interact with the live application. One just has to remember to
935 re-enable the mainloop call when running in standard Python.
936
937 Running without a subprocess
938 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
939
940 By default, IDLE executes user code in a separate subprocess via a socket,
941 which uses the internal loopback interface. This connection is not
942 externally visible and no data is sent to or received from the internet.
943 If firewall software complains anyway, you can ignore it.
944
945 If the attempt to make the socket connection fails, Idle will notify you.
946 Such failures are sometimes transient, but if persistent, the problem
947 may be either a firewall blocking the connection or misconfiguration of
948 a particular system. Until the problem is fixed, one can run Idle with
949 the -n command line switch.
950
951 If IDLE is started with the -n command line switch it will run in a
952 single process and will not create the subprocess which runs the RPC
953 Python execution server. This can be useful if Python cannot create
954 the subprocess or the RPC socket interface on your platform. However,
955 in this mode user code is not isolated from IDLE itself. Also, the
956 environment is not restarted when Run/Run Module (F5) is selected. If
957 your code has been modified, you must reload() the affected modules and
958 re-import any specific items (e.g. from foo import baz) if the changes
959 are to take effect. For these reasons, it is preferable to run IDLE
960 with the default subprocess if at all possible.
961
962 .. deprecated:: 3.4
963
964
965 Help and Preferences
966 --------------------
967
968 .. _help-sources:
969
970 Help sources
971 ^^^^^^^^^^^^
972
973 Help menu entry "IDLE Help" displays a formatted html version of the
974 IDLE chapter of the Library Reference. The result, in a read-only
975 tkinter text window, is close to what one sees in a web browser.
976 Navigate through the text with a mousewheel,
977 the scrollbar, or up and down arrow keys held down.
978 Or click the TOC (Table of Contents) button and select a section
979 header in the opened box.
980
981 Help menu entry "Python Docs" opens the extensive sources of help,
982 including tutorials, available at ``docs.python.org/x.y``, where 'x.y'
983 is the currently running Python version. If your system
984 has an off-line copy of the docs (this may be an installation option),
985 that will be opened instead.
986
987 Selected URLs can be added or removed from the help menu at any time using the
988 General tab of the Configure IDLE dialog.
989
990 .. _preferences:
991
992 Setting preferences
993 ^^^^^^^^^^^^^^^^^^^
994
995 The font preferences, highlighting, keys, and general preferences can be
996 changed via Configure IDLE on the Option menu.
997 Non-default user settings are saved in a ``.idlerc`` directory in the user's
998 home directory. Problems caused by bad user configuration files are solved
999 by editing or deleting one or more of the files in ``.idlerc``.
1000
1001 On the Font tab, see the text sample for the effect of font face and size
1002 on multiple characters in multiple languages. Edit the sample to add
1003 other characters of personal interest. Use the sample to select
1004 monospaced fonts. If particular characters have problems in Shell or an
1005 editor, add them to the top of the sample and try changing first size
1006 and then font.
1007
1008 On the Highlights and Keys tab, select a built-in or custom color theme
1009 and key set. To use a newer built-in color theme or key set with older
1010 IDLEs, save it as a new custom theme or key set and it well be accessible
1011 to older IDLEs.
1012
1013 IDLE on macOS
1014 ^^^^^^^^^^^^^
1015
1016 Under System Preferences: Dock, one can set "Prefer tabs when opening
1017 documents" to "Always". This setting is not compatible with the tk/tkinter
1018 GUI framework used by IDLE, and it breaks a few IDLE features.
1019
1020 Extensions
1021 ^^^^^^^^^^
1022
1023 IDLE contains an extension facility. Preferences for extensions can be
1024 changed with the Extensions tab of the preferences dialog. See the
1025 beginning of config-extensions.def in the idlelib directory for further
1026 information. The only current default extension is zzdummy, an example
1027 also used for testing.
1028
1029
1030 idlelib --- implementation of IDLE application
1031 ----------------------------------------------
1032
1033 .. module:: idlelib
1034 :synopsis: Implementation package for the IDLE shell/editor.
1035
1036 **Source code:** :source:`Lib/idlelib`
1037
1038 --------------
1039
1040 The Lib/idlelib package implements the IDLE application. See the rest
1041 of this page for how to use IDLE.
1042
1043 The files in idlelib are described in idlelib/README.txt. Access it
1044 either in idlelib or click Help => About IDLE on the IDLE menu. This
1045 file also maps IDLE menu items to the code that implements the item.
1046 Except for files listed under 'Startup', the idlelib code is 'private' in
1047 sense that feature changes can be backported (see :pep:`434`).