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