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