Idle shell python что это
Перейти к содержимому

Idle shell python что это

  • автор:

Idle shell python что это

IDLE — это интегрированная среда разработки и обучения Python.

У IDLE следующие особенности:

  • реализован на 100% чистом Python с использованием набора инструментов графического интерфейса пользователя tkinter
  • кросс-платформенный: работает практически одинаково в Windows, Unix и macOS
  • окно оболочки Python (интерактивный интерпретатор) с раскрашиванием ввода, вывода кода и сообщений об ошибках
  • многооконный текстовый редактор с несколькими отменами, раскрашиванием Python, интеллектуальным отступом, подсказками при вызове, автозавершением и другими функциями
  • поиск в любом окне, замена в окнах редактора и поиск в нескольких файлах (grep)
  • отладчик с постоянными точками останова, пошаговым выполнением и просмотром глобальных и локальных пространств имён
  • настройки, браузеры и другие диалоги

У IDLE два основных типа окон: окно оболочки и окно редактора. Одновременно можно создать несколько окон редактора. В Windows и Linux у каждого есть собственное верхнее меню. Каждое меню, задокументированное ниже, указывает, с каким типом окна оно связано.

Окна вывода, такие как Edit => Find в файлах, являются подтипом окна редактора. В настоящее время они имеют одно и то же верхнее меню, но другой заголовок по умолчанию и контекстное меню.

В macOS есть одно меню приложений. Он динамически изменяется в соответствии с выбранным в данный момент окном. В нем есть меню IDLE, а некоторые описанные ниже элементы, перемещены в соответствии с рекомендациями Apple.

Меню «File» (оболочка и редактор)¶

Меню «Edit» (Оболочка и Редактор)¶

Функции буфера обмена также доступны в контекстных меню.

Select All Выделяет все содержимое текущего окна. Find… Открывает диалоговое окно поиска с множеством параметров Find Again Повторяет последний поиск, если он есть. Find Selection Поиск текущей выбранной строки, если она есть. Find in Files… Открывает диалоговое окно поиска файлов. Помещает результаты в новое окно вывода. Replace… Открывает диалоговое окно поиска и замены. Go to Line Перемещает курсор в начало запрошенной строки и выполняет отображение строки. Запрос после конца файла перемещается в конец. Снимает выделение и обновляет статус строки и столбца. Show Completions Открывает прокручиваемый список, позволяющий выбрать существующие имена. См. Завершения в разделе «Редактирование и навигация» ниже. Expand Word Расширяет введенный вами префикс, чтобы он соответствовал полному слову в том же окне; повторяет, чтобы получить другое расширение. Show call tip После незакрытой скобки для функции открывает маленькое окно с подсказками параметров функции. См. Подсказки по вызову в разделе редактирования и навигации ниже. Show surrounding parens Подсвечивает окружающие скобки.

Меню «Format» (только окно редактора)¶

Меню «Run» (только окно редактора)¶

Меню «Shell» (только окно оболочки)¶

Меню «Debug» (только окно оболочки)¶

Меню «Options» (оболочка и редактор)¶

Большинство параметров конфигурации применяются ко всем окнам или ко всем будущим окнам. Пункты опций ниже применимы только к активному окну.

Show/Hide Code Context (Editor Window only) Открывает панель в верхней части окна редактирования, показывающая контекст блока кода, который прокручивается над верхней частью окна. См. Контекст кода в разделе «Редактирование и навигация» далее. Show/Hide Line Numbers (Editor Window only) Открывает столбец слева от окна редактирования, в котором отображается число каждой строки текста. По умолчанию выключено, это можно изменить в файле предпочтения (см. Настройка предпочтений ). Zoom/Restore Height Переключает окно между нормальным размером и максимальной высотой. Начальный размер по умолчанию 40 строк по 80 символов, если не изменено на вкладке «General» Configure диалогового окна IDLE. Максимальная высота экрана определяется мгновенное развертывание окна при первом увеличении экрана. Изменение настроек экрана может сделать сохраненную высоту недействительной. Данный переключатель имеет никакого эффекта, когда окно развернуто.

Меню «Window» (оболочка и редактор)¶

Перечисляет имена всех открытых окон; выбрать один, чтобы вывести его на передний план (при необходимости деиконизируя его).

Меню «Help» (Shell и Editor)¶

Здесь можно добавить дополнительные источники справки с помощью диалогового окна «Configure IDLE» на вкладке «General». Дополнительные сведения о пунктах меню «Help» см. в подразделе Справка ниже.

Контекстные меню¶

Открывает контекстное меню, щелкнув правой кнопкой мыши в окне (удерживая нажатой клавишу Control в macOS). У контекстного меню есть стандартные функции буфера обмена и в меню «Edit».

Cut Копирует выделение в общесистемный буфер обмена; затем удаляет выделение. Copy Копирует выделение в общесистемный буфер обмена. Paste Вставляет содержимое общесистемного буфера обмена в текущем окне.

У окон редактора также есть функции точек останова. Строки с установленной точкой останова помечаются специальным образом. Точки останова действуют только при работе под отладчиком. Точки останова для файла сохраняются в пользовательском каталоге .idlerc .

Set Breakpoint Устанавливает точку останова на текущей строке. Clear Breakpoint Очищает точку останова на данной строке.

Окна Shell и Output также содержат следующее:

Go to file/line То же, что и в меню отладки.

Окно Shell также содержит средство сжатия вывода, рассмотренное в подразделе Окно оболочки Python далее.

Squeeze Если курсор находится над строкой вывода, вставляет весь вывод между кодом выше и подсказкой ниже до метки «Squeezed text».

Редактирование и навигация¶

Окна редактора¶

IDLE может открывать окна редактора при запуске, в зависимости от настроек и способа запуска IDLE. После этого используйте меню «File». Для данного файла может быть только одно открытое окно редактора.

Строка заголовка содержит имя файла, полный путь и версию Python и IDLE, в которых запущено окно. Строка состояния содержит номер строки («Ln») и номер столбца («Col»). Номера строк начинаются с 1; номера столбцов с 0.

IDLE предполагает, что файлы с известным расширением .py* содержат код Python, а другие файлы — нет. Выполняет код Python с помощью меню «Run».

Привязки клавиш¶

В этом разделе «C» относится к клавише Control в Windows и Unix и клавише Command в macOS.

Backspace удаляет слева; Del удаляет вправо

C-Backspace удаляет слово слева; C-Del удаляет слово справа

Клавиши со стрелками и Page Up / Page Down для перемещения

C-LeftArrow и C-RightArrow перемещаются по словам

Home / End переходит к началу/концу строки

C-Home / C-End переходит к началу/концу файла

Некоторые полезные привязки Emacs унаследованы от Tcl/Tk:

  • C-a начало строки
  • C-e конец строки
  • Строка уничтожения C-k (но не помещается в буфер обмена)
  • C-l центральное окно вокруг точки вставки
  • C-b переходит на один символ назад без удаления (обычно для этого также можно использовать клавишу курсора)
  • C-f переходит на один символ вперед без удаления (обычно для этого также можно использовать клавишу курсора)
  • C-p переходит на одну строку вверх (обычно для этого также можно использовать клавишу курсора)
  • C-d удаляет следующий символ

Стандартные сочетания клавиш (например, C-c для копирования и C-v для вставки) могут работать. Привязки клавиш выбираются в диалоговом окне «Configure IDLE».

Автоматический отступ¶

После оператора открытия блока следующая строка имеет отступ в 4 пробела (в окне Python Shell на один таб). После определённых ключевых слов (break, return и т. д.) следующая строка содержит отступ. В начальном отступе Backspace удаляет до 4 пробелов, если они есть. Tab вставляет пробелы (в окне Python Shell один таб), количество зависит от ширины отступа. В настоящее время табы ограничены четырьмя пробелами из-за ограничений Tcl/Tk.

См. также команды indent/dedent области на странице Меню форматирования .

Завершения¶

Завершения предоставляются, когда они запрошены и доступны для имён модулей, атрибутов классов, функций или имён файлов. Каждый запрашиваемый метод отображает поле завершения с существующими именами. (Исключение см. ниже для заполнения табов.) Для любого поля изменяет заполняемое имя и элемент, выделенный в поле, введя и удалив символы; нажав клавиши Up , Down , PageUp , PageDown , Home и End ; и одним щелчком внутри поля. Закрывает окно клавишами Escape , Enter и двойными клавишами Tab или щелчками за пределами поля. Двойной щелчок внутри поля выбирает и закрывает.

Один из способов открыть поле — ввести ключевой символ и подождать заранее заданный интервал. По умолчанию — 2 секунды; настройте его в диалоге настроек. (Чтобы предотвратить автоматические всплывающие окна, устанавливает задержку на большое количество миллисекунд, например 100000000.) Для импортированных имён модулей или атрибутов класса или функции введите «.». Для имён файлов в корневом каталоге введите os.sep или os.altsep сразу после открывающей кавычки. (В Windows можно сначала указать диск.) Переходит в подкаталоги, введя имя каталога и разделитель.

Вместо того, чтобы ждать или после закрытия окна, немедленно открывает окно завершения с помощью команды «Show Completions» в меню «Edit». Горячая клавиша по умолчанию — C-space . Если перед открытием коробки ввести префикс для нужного имени, первое совпадение или близкое совпадение становится видимым. Результат такой же, как если бы кто-то ввел префикс после отображения окна. Показывает завершения после того, как кавычка завершает имена файлов в текущем каталоге, а не в корневом каталоге.

Нажатие Tab после префикса обычно имеет тот же эффект, что и «Show Completions». (Без префикса он — отступ.) Однако, если есть только одно совпадение с префиксом, это совпадение немедленно добавляется в текст редактора, не открывая поле.

Вызов «Show Completions» или нажатие Tab после префикса вне строки и без предшествующего «.». открывает поле с ключевыми словами, встроенными именами и доступными именами на уровне модуля.

При редактировании кода в редакторе (в отличие от Shell) увеличивает доступные имена на уровне модулей, запустив свой код и не перезапуская Shell после него. Это особенно полезно после добавления импорта в начало файла. Это также увеличивает количество возможных завершений атрибутов.

Поля завершения изначально исключают имена, начинающиеся с «_» или, для модулей, не включенные в «__all__». Доступ к скрытым именам можно получить, набрав «_» после «.» либо до, либо после открытия поля.

Подсказки¶

Подсказка отображается автоматически при вводе ( после имени доступной функции. Выражение имени функции может включать точки и нижние индексы. Подсказка остаётся до тех пор, пока по ней не будет нажат щелчок, курсор не будет перемещен за пределы области аргумента или не будет введено ) . Всякий раз, когда курсор находится в части аргумента определения, выберите «Edit» и «Show Call Tip» в меню или введите его ярлык, чтобы отобразить подсказку.

Подсказка состоит из сигнатуры функции и строки документации до первой пустой строки последней или до пятой непустой строки. (Некоторые встроенные функции не имеют доступной сигнатуры.) «/» или «*» в сигнатуре указывает, что предшествующие или последующие аргументы передаются только по положению или имени (ключевому слову). Детали могут быть изменены.

В Shell доступные функции зависят от того, какие модули были импортированы в пользовательский процесс, в том числе импортированные самим Idle, и какие определения были запущены с момента последнего перезапуска.

Например, перезапустите Shell и введите itertools.count( . Подсказка появляется, потому что Idle импортирует itertools в пользовательский процесс для собственного использования. (Это может измениться.) Введите turtle.write( , и ничего не появится. Простой сам по себе не импортирует turtle. Вход в меню и ярлык тоже ничего не делают. Введите import turtle . После этого turtle.write( отобразит всплывающую подсказку.

В редакторе операторы импорта не действуют до тех пор, пока файл не будет запущен. Может потребоваться запустить файл после написания операторов импорта, после добавления определений функций или после открытия существующего файла.

Контекст кода¶

В окне содержащем код Python редактора, можно переключать контекст кода, чтобы отобразить или скрыть панель в верхней части окна. При отображении данная панель замораживает начальные строки для блочного кода, например начинающиеся с ключевых слов class , def или if , которые в противном случае прокручивались бы вне поля зрения. Размер панели будет увеличиваться и уменьшаться по мере необходимости, чтобы отображать все текущие уровни контекста, вплоть до максимального количества строк, определённого в диалоговом окне «Configure IDLE» (которое по умолчанию равно 15). Если текущих строк контекста нет, а функция включена, будет отображаться одна пустая строка. Щелчок по строке в контекстной панели переместит эту строку в верхнюю часть редактора.

Цвета текста и фона контекстной панели можно настроить на вкладке «Highlights» в диалоговом окне «Configure IDLE».

Окно Shell Python¶

С оболочкой IDLE можно вводить, редактировать и вызывать завершенные операторы. Большинство консолей и терминалов одновременно работают только с одной физической строкой.

Когда кто-то вставляет код в Shell, он не компилируется и, возможно, не выполняется до тех пор, пока не будет найден Return . Сначала можно отредактировать вставленный код. Если вставить в Shell более одного оператора, результатом будет SyntaxError , когда несколько операторов скомпилированы, как если бы они были одним.

Функции редактирования, описанные в предыдущих подразделах, работают при интерактивном вводе кода. Окно оболочки IDLE также реагирует на следующие клавиши.

C-c прерывает выполнение команды

C-d отправляет конец файла; закрывает окно, если введено в приглашении >>>

Alt-/ (Расширенное слово) также удобен для сокращения набора текста

  • Alt-p извлекает предыдущую команду, соответствующую тому, что вы набрали. В macOS используйте C-p .
  • Alt-n получает следующее. В macOS используйте C-n .
  • Return во время любой предыдущей команды извлекает эту команду.

Цвета текста¶

В Idle по умолчанию текст отображается черным цветом на белом фоне, но при этом текст окрашивается в специальные цвета. Для оболочки это вывод оболочки, ошибка оболочки, вывод пользователя и ошибка пользователя. Для кода Python в командной строке или в редакторе это ключевые слова, имена встроенных классов и функций, имена после class и def , строки и комментарии. Для любого текстового окна это курсор (если присутствует), найденный текст (если возможно) и выделенный текст.

Раскрашивание текста выполняется в фоновом режиме, поэтому иногда виден неокрашенный текст. Чтобы изменить цветовую схему, используйте вкладку Highlighting диалогового окна Configure IDLE. Отметка строк точки останова отладчика в редакторе и текста во всплывающих окнах и диалогах не настраивается пользователем.

Запуск и выполнение кода¶

При запуске с параметром -s IDLE выполнит файл, на который ссылаются переменные среды IDLESTARTUP или PYTHONSTARTUP . IDLE сначала проверяет IDLESTARTUP ; если присутствует IDLESTARTUP , запускается указанный файл. Если IDLESTARTUP отсутствует, IDLE проверяет наличие PYTHONSTARTUP . Файлы, на которые ссылаются данные переменные среды, являются удобными местами для хранения часто используемых из оболочки IDLE функций, или для выполнения операторов импорта для импорта общих модулей.

Кроме того, Tk также загружает файл запуска, если он присутствует. Обратите внимание, что файл Tk загружается безоговорочно. Данный дополнительный файл имеет номер .Idle.py и ищется в домашнем каталоге пользователя. Операторы в этом файле будут выполняться в пространстве имён Tk, поэтому данный файл не подходит для импорта функций, которые будут использоваться из оболочки Python IDLE.

Использование командной строки¶

Если есть аргументы:

  • Если используется — , -c или r , все аргументы помещаются в sys.argv[1. ] , а sys.argv[0] устанавливается в » , ‘-c’ или ‘-r’ . Окно редактора не открывается, даже если это установлено по умолчанию в диалоговом окне «Options».
  • В противном случае аргументы — это файлы, открытые для редактирования, а sys.argv отражает аргументы, переданные самой IDLE.

Ошибка запуска¶

IDLE использует сокет для связи между процессом пользовательского интерфейса IDLE и процессом выполнения пользовательского кода. Соединение должно устанавливаться при каждом запуске или перезапуске Shell. (Последнее обозначено разделительной линией с надписью «RESTART»). Если пользовательскому процессу не удается подключиться к процессу пользовательского интерфейса, он отображает окно ошибки Tk с сообщением «невозможно подключиться (cannot connect)», которое направляет пользователя сюда. Затем он выходит.

Распространенной причиной сбоя является написанный пользователем файл с тем же именем, что и у модуля стандартной библиотеки, например random.py и tkinter.py. Когда такой файл находится в том же каталоге, что и файл, который должен быть запущен, IDLE не может импортировать файл stdlib. Текущее исправление заключается в переименовании файла пользователя.

Хотя реже, чем в прошлом, антивирусная программа или брандмауэр могут прервать соединение. Если программу нельзя научить разрешать соединение, то для работы IDLE её необходимо отключить. Безопасно разрешать это внутреннее соединение, потому что никакие данные не видны на внешних портах. Аналогичной проблемой является неправильная конфигурация сети, которая блокирует соединения.

Проблемы с установкой Python иногда останавливают IDLE: несколько версий могут конфликтовать, или для одной установки может потребоваться доступ администратора. Если кто-то отменяет конфликт или не может или не хочет работать от имени администратора, проще всего полностью удалить Python и начать заново.

Зомби процесс pythonw.exe может быть проблемой. В Windows используйте диспетчер задач, чтобы проверить его и остановить, если он есть. Иногда перезагрузка, инициированная сбоем программы или прерыванием клавиатуры (control-C), может не подключиться. Закрытие окна ошибки или использование «Restart Shell» в меню «Shell» может решить временную проблему.

При первом запуске IDLE пытается прочитать файлы конфигурации пользователя в

— домашний каталог). В случае возникновения проблемы должно появиться сообщение об ошибке. Не говоря уже о случайных сбоях диска, этого можно избежать, никогда не редактируйте файлы вручную. Вместо этого используйте диалоговое окно конфигурации в разделе «Options». Если в файле конфигурации пользователя есть ошибка, лучшим решением может быть его удаление и запуск диалога настроек заново.

Если IDLE завершается без сообщения и не был запущен из консоли, попробуйте запустить его из консоли или терминала ( python -m idlelib ) и посмотрите, не приведёт ли это к появлению сообщения об ошибке.

Запуск пользовательского кода¶

За редкими исключениями, результат выполнения кода Python с помощью IDLE должен быть таким же, как и при выполнении того же кода методом по умолчанию, непосредственно с помощью Python в текстовой системной консоли или окне терминала. Однако другой интерфейс и работа иногда влияют на видимые результаты. Например, sys.modules начинается с большего количества записей, а threading.activeCount() возвращает 2 вместо 1.

По умолчанию IDLE запускает пользовательский код в отдельном процессе ОС, а не в процессе пользовательского интерфейса, который запускает оболочку и редактор. В процессе выполнения он заменяет sys.stdin , sys.stdout и sys.stderr объектами, которые получают ввод и отправляют вывод в окно Shell. Исходные значения, хранящиеся в sys.__stdin__ , sys.__stdout__ и sys.__stderr__ , не изменяются, но могут быть None .

Когда Shell получает фокус, он управляет клавиатурой и экраном. Обычно это прозрачно, но обращающиеся напрямую к клавиатуре и экрану функции, работать не будут. К ним относятся специфичные для системы функции, которые определяют, была ли нажата клавиша, и если да, то какая.

Стандартные замены потоков IDLE не наследуются подпроцессами, созданными в процессе выполнения, будь то непосредственно пользовательский код или модули, такие как multiprocessing. Если такой подпроцесс использует input из sys.stdin или print или write в sys.stdout или sys.stderr, IDLE следует запустить в окне командной строки. Затем вторичный подпроцесс будет присоединен к этому окну для ввода и вывода.

Код IDLE, работающий в процессе выполнения, добавляет фреймы в стек вызовов, которых в противном случае там не было бы. IDLE переносит sys.getrecursionlimit и sys.setrecursionlimit , чтобы уменьшить влияние дополнительных фреймов стека.

Если sys сбрасывается кодом пользователя, например, importlib.reload(sys) , изменения IDLE теряются, а ввод с клавиатуры и вывод на экран не будут работать правильно.

Когда пользовательский код вызывает SystemExit либо напрямую, либо путём вызова sys.exit, IDLE вместо выхода возвращается к приглашению оболочки.

Пользовательский вывод в Shell¶

Когда программа выводит текст, результат определяется соответствующим устройством вывода. Когда IDLE выполняет пользовательский код, sys.stdout и sys.stderr подключаются к области отображения оболочки IDLE. Некоторые из его функций унаследованы от базового виджета Tk Text. Другие являются запрограммированными дополнениями. Там, где это важно, Shell предназначена для разработки, а не для производственного запуска.

Например, Shell никогда не выбрасывает выходные данные. Программа, которая отправляет неограниченный вывод в Shell, в конечном итоге заполнит память, что приведёт к ошибке памяти. Напротив, некоторые системные текстовые окна сохраняют только последние n строк вывода. Консоль Windows, например, сохраняет настраиваемое пользователем от 1 до 9999 строк, по умолчанию 300.

Виджет Tk Text и, следовательно, оболочка IDLE отображает символы (кодовые точки) в подмножестве Юникод BMP (Basic Multilingual Plane). Какие символы отображаются с правильным глифом, а какие с замещающим полем, зависит от операционной системы и установленных шрифтов. Символы табуляции заставляют следующий текст начинаться после следующей позиции табуляции. (Они встречаются каждые 8 «символов»). Символы новой строки заставляют следующий текст появляться на новой строке. Другие управляющие символы игнорируются или отображаются как пробел, прямоугольник или что-то ещё, в зависимости от операционной системы и шрифта. (Перемещение текстового курсора по такому выводу с помощью клавиш со стрелками может привести к неожиданному поведению пробелов.)

Функция repr используется для интерактивного отображения значений выражений. Она возвращает измененную версию входной строки, в которой управляющие коды, некоторые кодовые точки BMP и все кодовые точки, отличные от BMP, заменены управляющими кодами. Как показано выше, она позволяет идентифицировать символы в строке независимо от того, как они отображаются.

Нормальный вывод и вывод ошибок обычно хранятся отдельно (в отдельных строках) от ввода кода и друг от друга. Каждый из них получает разные цвета подсветки.

Для трассировки SyntaxError обычная отметка «^» в месте обнаружения ошибки заменяется выделением текста цветом ошибки. Когда запускаемый из файла код, вызывает другие исключения, можно щелкнуть правой кнопкой мыши строку трассировки, чтобы перейти к соответствующей строке в IDLE редакторе. Файл будет открыт при необходимости.

В Shell есть специальное средство для сжатия строк вывода до метки «Squeezed text». Это делается автоматически для вывода на N строк (N = 50 по умолчанию). N можно изменить в разделе PyShell на странице «General» диалогового окна «Settings». Вывод с меньшим количеством строк можно сжать, щелкнув правой кнопкой мыши на выводе. Это могут быть полезные строки, достаточно длинные, чтобы замедлить прокрутку.

Сжатый вывод расширяется на месте двойным щелчком метки. Его также можно отправить в буфер обмена или отдельное окно просмотра, щелкнув метку правой кнопкой мыши.

Разработка tkinter приложений¶

IDLE намеренно отличается от стандартного Python, чтобы облегчить разработку программ tkinter. Введите import tkinter as tk; root = tk.Tk() в стандартном Python, и ничего не появится. Введите то же самое в IDLE, и появится окно tk. В стандартном Python нужно также ввести root.update() , чтобы увидеть окно. IDLE делает то же самое в фоновом режиме примерно 20 раз в секунду, т. е. примерно каждые 50 миллисекунд. Затем наберите b = tk.Button(root, text=’button’); b.pack() . Опять же, в стандартном Python ничего не меняется, пока не будет root.update() .

Большинство программ tkinter запускают root.mainloop() , который обычно не возвращается, пока приложение tk не будет уничтожено. Если программа запускается с python -i или из редактора IDLE, приглашение оболочки >>> не появляется до тех пор, пока не вернется mainloop() , после чего взаимодействовать не с чем.

При запуске tkinter программы из редактора IDLE можно закомментировать вызов mainloop. Затем вы сразу же получаете приглашение оболочки и можете взаимодействовать с живым приложением. Просто нужно не забыть снова включить вызов mainloop при работе в стандартном Python.

Запуск без подпроцесса¶

По умолчанию IDLE выполняет пользовательский код в отдельном подпроцессе через сокет, который использует внутренний петлевой (loopback) интерфейс. Это соединение не видно извне, и данные не отправляются и не принимаются из Интернета. Если программное обеспечение брандмауэра все равно жалуется, вы можете игнорировать его.

Если попытка установить подключение к сокету не удалась, Idle уведомит вас об этом. Такие сбои иногда носят временный характер, но если они сохраняются, проблема может заключаться либо в брандмауэре, блокирующем соединение, либо в неправильной настройке системы. Пока проблема не устранена, можно запускать Idle с опцией командной строки -n .

Если IDLE запущен с параметром командной строки -n , он будет работать в одном процессе и не будет создавать подпроцесс, который запускает сервер выполнения RPC Python. Это может быть полезно, если Python не может создать подпроцесс или RPC интерфейс сокета на вашей платформе. Однако в этом режиме пользовательский код не изолирован от самого IDLE. Кроме того, среда не перезапускается, когда выбрано «Run/Run Module» (F5). Если ваш код был изменён, вы должны reload() затронутые модули и повторно импортировать любые определённые элементы (например, из foo import baz), чтобы изменения вступили в силу. По этим причинам предпочтительнее запускать IDLE с подпроцессом по умолчанию, если это вообще возможно.

Не рекомендуется, начиная с версии 3.4.

Помощь и предпочтения¶

Источники помощи¶

Пункт меню «Help» «IDLE Help» отображает отформатированную html-версию главы IDLE Справочника по библиотеке. Результат в текстовом окне tkinter, доступном только для чтения, близок к тому, что можно увидеть в браузере. Перемещайтесь по тексту с помощью колесика мыши, полосы прокрутки или клавиш со стрелками вверх и вниз, удерживая их нажатыми. Или нажмите кнопку TOC (Оглавление) и выбрать заголовок раздела в открывшемся окне.

Пункт меню справки «Python Docs» открывает обширные источники справки, включая учебные пособия, доступные по адресу docs.python.org/x.y , где «x.y» — это текущая версия Python. Если в вашей системе есть автономная копия документов (это может быть вариант установки), вместо этого будет открыта она.

Выбранные URL-адреса могут быть добавлены или удалены из меню справки в любое время с помощью табы «General» диалогового окна «Configure IDLE».

Установка предпочтений¶

Параметры шрифта, подсветка, клавиши и общие параметры можно изменить с помощью пункта «Configure IDLE» в меню «Option». Пользовательские настройки, отличные от настроек по умолчанию, сохраняются в каталоге .idlerc в домашнем каталоге пользователя. Проблемы, вызванные плохими файлами конфигурации пользователя, решаются путём редактирования или удаления одного или нескольких файлов в .idlerc .

На вкладке «Font» см. пример текста, в котором показано влияние начертания и размера шрифта на несколько символов на разных языках. Отредактируйте образец, чтобы добавить других символов, представляющих личный интерес. Используйте образец для выбора моноширинных шрифтов. Если у определённых символов есть проблемы в Shell или редакторе, добавьте их в начало образца и попробуйте изменить сначала размер, а затем шрифт.

На вкладке «Highlights and Keys» выберите встроенную или пользовательскую цветовую тему и множество клавиш. Чтобы использовать более новую встроенную цветовую тему или набор клавиш со старыми IDLE, сохранить их как новую пользовательскую тему или набор клавиш, и они будут доступны для более старых IDLE.

IDLE на macOS¶

В разделе «System Preferences: Dock» можно установить «Prefer tabs when opening documents» на «Always». Данный параметр несовместим с инфраструктурой графического интерфейса пользователя tk/tkinter, используемой IDLE, и нарушает некоторые функции IDLE.

Idle shell python что это

Source code: Lib/idlelib/

IDLE is Python’s Integrated Development and Learning Environment.

IDLE has the following features:

coded in 100% pure Python, using the tkinter GUI toolkit

cross-platform: works mostly the same on Windows, Unix, and macOS

Python shell window (interactive interpreter) with colorizing of code input, output, and error messages

multi-window text editor with multiple undo, Python colorizing, smart indent, call tips, auto completion, and other features

search within any window, replace within editor windows, and search through multiple files (grep)

debugger with persistent breakpoints, stepping, and viewing of global and local namespaces

configuration, browsers, and other dialogs

Menus¶

IDLE has two main window types, the Shell window and the Editor window. It is possible to have multiple editor windows simultaneously. On Windows and Linux, each has its own top menu. Each menu documented below indicates which window type it is associated with.

Output windows, such as used for Edit => Find in Files, are a subtype of editor window. They currently have the same top menu but a different default title and context menu.

On macOS, there is one application menu. It dynamically changes according to the window currently selected. It has an IDLE menu, and some entries described below are moved around to conform to Apple guidelines.

File menu (Shell and Editor)¶

Create a new file editing window.

Open an existing file with an Open dialog.

Open an existing module (searches sys.path).

Open a list of recent files. Click one to open it.

Show functions, classes, and methods in the current Editor file in a tree structure. In the shell, open a module first.

Show sys.path directories, modules, functions, classes and methods in a tree structure.

Save the current window to the associated file, if there is one. Windows that have been changed since being opened or last saved have a * before and after the window title. If there is no associated file, do Save As instead.

Save the current window with a Save As dialog. The file saved becomes the new associated file for the window. (If your file namager is set to hide extensions, the current extension will be omitted in the file name box. If the new filename has no ‘.’, ‘.py’ and ‘.txt’ will be added for Python and text files, except that on macOS Aqua,’.py’ is added for all files.)

Save the current window to different file without changing the associated file. (See Save As note above about filename extensions.)

Print the current window to the default printer.

Close the current window (if an unsaved editor, ask to save; if an unsaved Shell, ask to quit execution). Calling exit() or close() in the Shell window also closes Shell. If this is the only window, also exit IDLE.

Close all windows and quit IDLE (ask to save unsaved edit windows).

Edit menu (Shell and Editor)¶

Undo the last change to the current window. A maximum of 1000 changes may be undone.

Redo the last undone change to the current window.

Select the entire contents of the current window.

Copy selection into the system-wide clipboard; then delete the selection.

Copy selection into the system-wide clipboard.

Insert contents of the system-wide clipboard into the current window.

The clipboard functions are also available in context menus.

Open a search dialog with many options

Repeat the last search, if there is one.

Search for the currently selected string, if there is one.

Open a file search dialog. Put results in a new output window.

Open a search-and-replace dialog.

Move the cursor to the beginning of the line requested and make that line visible. A request past the end of the file goes to the end. Clear any selection and update the line and column status.

Open a scrollable list allowing selection of existing names. See Completions in the Editing and navigation section below.

Expand a prefix you have typed to match a full word in the same window; repeat to get a different expansion.

After an unclosed parenthesis for a function, open a small window with function parameter hints. See Calltips in the Editing and navigation section below.

Show Surrounding Parens

Highlight the surrounding parenthesis.

Format menu (Editor window only)¶

Reformat the current blank-line-delimited paragraph in comment block or multiline string or selected line in a string. All lines in the paragraph will be formatted to less than N columns, where N defaults to 72.

Shift selected lines right by the indent width (default 4 spaces).

Shift selected lines left by the indent width (default 4 spaces).

Comment Out Region

Insert ## in front of selected lines.

Remove leading # or ## from selected lines.

Turn leading stretches of spaces into tabs. (Note: We recommend using 4 space blocks to indent Python code.)

Turn all tabs into the correct number of spaces.

Open a dialog to switch between indenting with spaces and tabs.

New Indent Width

Open a dialog to change indent width. The accepted default by the Python community is 4 spaces.

Strip Trailing Chitespace

Remove trailing space and other whitespace characters after the last non-whitespace character of a line by applying str.rstrip to each line, including lines within multiline strings. Except for Shell windows, remove extra newlines at the end of the file.

Run menu (Editor window only)¶

Do Check Module . If no error, restart the shell to clean the environment, then execute the module. Output is displayed in the Shell window. Note that output requires use of print or write . When execution is complete, the Shell retains focus and displays a prompt. At this point, one may interactively explore the result of execution. This is similar to executing a file with python -i file at a command line.

Same as Run Module , but run the module with customized settings. Command Line Arguments extend sys.argv as if passed on a command line. The module can be run in the Shell without restarting.

Check the syntax of the module currently open in the Editor window. If the module has not been saved IDLE will either prompt the user to save or autosave, as selected in the General tab of the Idle Settings dialog. If there is a syntax error, the approximate location is indicated in the Editor window.

Open or wake up the Python Shell window.

Shell menu (Shell window only)¶

Scroll the shell window to the last Shell restart.

Restart the shell to clean the environment and reset display and exception handling.

Cycle through earlier commands in history which match the current entry.

Cycle through later commands in history which match the current entry.

Stop a running program.

Debug menu (Shell window only)¶

Look on the current line. with the cursor, and the line above for a filename and line number. If found, open the file if not already open, and show the line. Use this to view source lines referenced in an exception traceback and lines found by Find in Files. Also available in the context menu of the Shell window and Output windows.

When activated, code entered in the Shell or run from an Editor will run under the debugger. In the Editor, breakpoints can be set with the context menu. This feature is still incomplete and somewhat experimental.

Show the stack traceback of the last exception in a tree widget, with access to locals and globals.

Auto-open Stack Viewer

Toggle automatically opening the stack viewer on an unhandled exception.

Options menu (Shell and Editor)¶

Open a configuration dialog and change preferences for the following: fonts, indentation, keybindings, text color themes, startup windows and size, additional help sources, and extensions. On macOS, open the configuration dialog by selecting Preferences in the application menu. For more details, see Setting preferences under Help and preferences.

Most configuration options apply to all windows or all future windows. The option items below only apply to the active window.

Show/Hide Code Context (Editor Window only)

Open a pane at the top of the edit window which shows the block context of the code which has scrolled above the top of the window. See Code Context in the Editing and Navigation section below.

Show/Hide Line Numbers (Editor Window only)

Open a column to the left of the edit window which shows the number of each line of text. The default is off, which may be changed in the preferences (see Setting preferences ).

Toggles the window between normal size and maximum height. The initial size defaults to 40 lines by 80 chars unless changed on the General tab of the Configure IDLE dialog. The maximum height for a screen is determined by momentarily maximizing a window the first time one is zoomed on the screen. Changing screen settings may invalidate the saved height. This toggle has no effect when a window is maximized.

Window menu (Shell and Editor)¶

Lists the names of all open windows; select one to bring it to the foreground (deiconifying it if necessary).

Help menu (Shell and Editor)¶

Display version, copyright, license, credits, and more.

Display this IDLE document, detailing the menu options, basic editing and navigation, and other tips.

Access local Python documentation, if installed, or start a web browser and open docs.python.org showing the latest Python documentation.

Run the turtledemo module with example Python code and turtle drawings.

Additional help sources may be added here with the Configure IDLE dialog under the General tab. See the Help sources subsection below for more on Help menu choices.

Context menus¶

Open a context menu by right-clicking in a window (Control-click on macOS). Context menus have the standard clipboard functions also on the Edit menu.

Copy selection into the system-wide clipboard; then delete the selection.

Copy selection into the system-wide clipboard.

Insert contents of the system-wide clipboard into the current window.

Editor windows also have breakpoint functions. Lines with a breakpoint set are specially marked. Breakpoints only have an effect when running under the debugger. Breakpoints for a file are saved in the user’s .idlerc directory.

Set a breakpoint on the current line.

Clear the breakpoint on that line.

Shell and Output windows also have the following.

Same as in Debug menu.

The Shell window also has an output squeezing facility explained in the Python Shell window subsection below.

If the cursor is over an output line, squeeze all the output between the code above and the prompt below down to a ‘Squeezed text’ label.

Editing and Navigation¶

Editor windows¶

IDLE may open editor windows when it starts, depending on settings and how you start IDLE. Thereafter, use the File menu. There can be only one open editor window for a given file.

The title bar contains the name of the file, the full path, and the version of Python and IDLE running the window. The status bar contains the line number (‘Ln’) and column number (‘Col’). Line numbers start with 1; column numbers with 0.

IDLE assumes that files with a known .py* extension contain Python code and that other files do not. Run Python code with the Run menu.

Key bindings¶

In this section, ‘C’ refers to the Control key on Windows and Unix and the Command key on macOS.

Backspace deletes to the left; Del deletes to the right

C — Backspace delete word left; C — Del delete word to the right

Arrow keys and Page Up / Page Down to move around

C — LeftArrow and C — RightArrow moves by words

Home / End go to begin/end of line

C — Home / C — End go to begin/end of file

Some useful Emacs bindings are inherited from Tcl/Tk:

  • C — a beginning of line

  • C — e end of line

  • C — k kill line (but doesn’t put it in clipboard)

  • C — l center window around the insertion point

  • C — b go backward one character without deleting (usually you can also use the cursor key for this)

  • C — f go forward one character without deleting (usually you can also use the cursor key for this)

  • C — p go up one line (usually you can also use the cursor key for this)

  • C — d delete next character

Standard keybindings (like C — c to copy and C — v to paste) may work. Keybindings are selected in the Configure IDLE dialog.

Automatic indentation¶

After a block-opening statement, the next line is indented by 4 spaces (in the Python Shell window by one tab). After certain keywords (break, return etc.) the next line is dedented. In leading indentation, Backspace deletes up to 4 spaces if they are there. Tab inserts spaces (in the Python Shell window one tab), number depends on Indent width. Currently, tabs are restricted to four spaces due to Tcl/Tk limitations.

See also the indent/dedent region commands on the Format menu .

Search and Replace¶

Any selection becomes a search target. However, only selections within a line work because searches are only performed within lines with the terminal newline removed. If [x] Regular expresion is checked, the target is interpreted according to the Python re module.

Completions¶

Completions are supplied, when requested and available, for module names, attributes of classes or functions, or filenames. Each request method displays a completion box with existing names. (See tab completions below for an exception.) For any box, change the name being completed and the item highlighted in the box by typing and deleting characters; by hitting Up , Down , PageUp , PageDown , Home , and End keys; and by a single click within the box. Close the box with Escape , Enter , and double Tab keys or clicks outside the box. A double click within the box selects and closes.

One way to open a box is to type a key character and wait for a predefined interval. This defaults to 2 seconds; customize it in the settings dialog. (To prevent auto popups, set the delay to a large number of milliseconds, such as 100000000.) For imported module names or class or function attributes, type ‘.’. For filenames in the root directory, type os.sep or os.altsep immediately after an opening quote. (On Windows, one can specify a drive first.) Move into subdirectories by typing a directory name and a separator.

Instead of waiting, or after a box is closed, open a completion box immediately with Show Completions on the Edit menu. The default hot key is C — space . If one types a prefix for the desired name before opening the box, the first match or near miss is made visible. The result is the same as if one enters a prefix after the box is displayed. Show Completions after a quote completes filenames in the current directory instead of a root directory.

Hitting Tab after a prefix usually has the same effect as Show Completions. (With no prefix, it indents.) However, if there is only one match to the prefix, that match is immediately added to the editor text without opening a box.

Invoking ‘Show Completions’, or hitting Tab after a prefix, outside of a string and without a preceding ‘.’ opens a box with keywords, builtin names, and available module-level names.

When editing code in an editor (as oppose to Shell), increase the available module-level names by running your code and not restarting the Shell thereafter. This is especially useful after adding imports at the top of a file. This also increases possible attribute completions.

Completion boxes initially exclude names beginning with ‘_’ or, for modules, not included in ‘__all__’. The hidden names can be accessed by typing ‘_’ after ‘.’, either before or after the box is opened.

Calltips¶

A calltip is shown automatically when one types ( after the name of an accessible function. A function name expression may include dots and subscripts. A calltip remains until it is clicked, the cursor is moved out of the argument area, or ) is typed. Whenever the cursor is in the argument part of a definition, select Edit and “Show Call Tip” on the menu or enter its shortcut to display a calltip.

The calltip consists of the function’s signature and docstring up to the latter’s first blank line or the fifth non-blank line. (Some builtin functions lack an accessible signature.) A ‘/’ or ‘*’ in the signature indicates that the preceding or following arguments are passed by position or name (keyword) only. Details are subject to change.

In Shell, the accessible functions depends on what modules have been imported into the user process, including those imported by Idle itself, and which definitions have been run, all since the last restart.

For example, restart the Shell and enter itertools.count( . A calltip appears because Idle imports itertools into the user process for its own use. (This could change.) Enter turtle.write( and nothing appears. Idle does not itself import turtle. The menu entry and shortcut also do nothing. Enter import turtle . Thereafter, turtle.write( will display a calltip.

In an editor, import statements have no effect until one runs the file. One might want to run a file after writing import statements, after adding function definitions, or after opening an existing file.

Code Context¶

Within an editor window containing Python code, code context can be toggled in order to show or hide a pane at the top of the window. When shown, this pane freezes the opening lines for block code, such as those beginning with class , def , or if keywords, that would have otherwise scrolled out of view. The size of the pane will be expanded and contracted as needed to show the all current levels of context, up to the maximum number of lines defined in the Configure IDLE dialog (which defaults to 15). If there are no current context lines and the feature is toggled on, a single blank line will display. Clicking on a line in the context pane will move that line to the top of the editor.

The text and background colors for the context pane can be configured under the Highlights tab in the Configure IDLE dialog.

Shell window¶

In IDLE’s Shell, enter, edit, and recall complete statements. (Most consoles and terminals only work with a single physical line at a time).

Submit a single-line statement for execution by hitting Return with the cursor anywhere on the line. If a line is extended with Backslash ( \ ), the cursor must be on the last physical line. Submit a multi-line compound statement by entering a blank line after the statement.

When one pastes code into Shell, it is not compiled and possibly executed until one hits Return , as specified above. One may edit pasted code first. If one pastes more than one statement into Shell, the result will be a SyntaxError when multiple statements are compiled as if they were one.

Lines containing RESTART mean that the user execution process has been re-started. This occurs when the user execution process has crashed, when one requests a restart on the Shell menu, or when one runs code in an editor window.

The editing features described in previous subsections work when entering code interactively. IDLE’s Shell window also responds to the following keys.

C — c interrupts executing command

C — d sends end-of-file; closes window if typed at a >>> prompt

Alt — / (Expand word) is also useful to reduce typing

Alt — p retrieves previous command matching what you have typed. On macOS use C — p .

Alt — n retrieves next. On macOS use C — n .

Return while the cursor is on any previous command retrieves that command

Text colors¶

Idle defaults to black on white text, but colors text with special meanings. For the shell, these are shell output, shell error, user output, and user error. For Python code, at the shell prompt or in an editor, these are keywords, builtin class and function names, names following class and def , strings, and comments. For any text window, these are the cursor (when present), found text (when possible), and selected text.

IDLE also highlights the soft keywords match , case , and _ in pattern-matching statements. However, this highlighting is not perfect and will be incorrect in some rare cases, including some _ -s in case patterns.

Text coloring is done in the background, so uncolorized text is occasionally visible. To change the color scheme, use the Configure IDLE dialog Highlighting tab. The marking of debugger breakpoint lines in the editor and text in popups and dialogs is not user-configurable.

Startup and Code Execution¶

Upon startup with the -s option, IDLE will execute the file referenced by the environment variables IDLESTARTUP or PYTHONSTARTUP . IDLE first checks for IDLESTARTUP ; if IDLESTARTUP is present the file referenced is run. If IDLESTARTUP is not present, IDLE checks for PYTHONSTARTUP . Files referenced by these environment variables are convenient places to store functions that are used frequently from the IDLE shell, or for executing import statements to import common modules.

In addition, Tk also loads a startup file if it is present. Note that the Tk file is loaded unconditionally. This additional file is .Idle.py and is looked for in the user’s home directory. Statements in this file will be executed in the Tk namespace, so this file is not useful for importing functions to be used from IDLE’s Python shell.

Command line usage¶

If there are arguments:

If — , -c , or r is used, all arguments are placed in sys.argv[1. ] and sys.argv[0] is set to » , ‘-c’ , or ‘-r’ . No editor window is opened, even if that is the default set in the Options dialog.

Otherwise, arguments are files opened for editing and sys.argv reflects the arguments passed to IDLE itself.

Startup failure¶

IDLE uses a socket to communicate between the IDLE GUI process and the user code execution process. A connection must be established whenever the Shell starts or restarts. (The latter is indicated by a divider line that says ‘RESTART’). If the user process fails to connect to the GUI process, it usually displays a Tk error box with a ‘cannot connect’ message that directs the user here. It then exits.

One specific connection failure on Unix systems results from misconfigured masquerading rules somewhere in a system’s network setup. When IDLE is started from a terminal, one will see a message starting with ** Invalid host: . The valid value is 127.0.0.1 (idlelib.rpc.LOCALHOST) . One can diagnose with tcpconnect -irv 127.0.0.1 6543 in one terminal window and tcplisten <same args> in another.

A common cause of failure is a user-written file with the same name as a standard library module, such as random.py and tkinter.py. When such a file is located in the same directory as a file that is about to be run, IDLE cannot import the stdlib file. The current fix is to rename the user file.

Though less common than in the past, an antivirus or firewall program may stop the connection. If the program cannot be taught to allow the connection, then it must be turned off for IDLE to work. It is safe to allow this internal connection because no data is visible on external ports. A similar problem is a network mis-configuration that blocks connections.

Python installation issues occasionally stop IDLE: multiple versions can clash, or a single installation might need admin access. If one undo the clash, or cannot or does not want to run as admin, it might be easiest to completely remove Python and start over.

A zombie pythonw.exe process could be a problem. On Windows, use Task Manager to check for one and stop it if there is. Sometimes a restart initiated by a program crash or Keyboard Interrupt (control-C) may fail to connect. Dismissing the error box or using Restart Shell on the Shell menu may fix a temporary problem.

When IDLE first starts, it attempts to read user configuration files in

is one’s home directory). If there is a problem, an error message should be displayed. Leaving aside random disk glitches, this can be prevented by never editing the files by hand. Instead, use the configuration dialog, under Options. Once there is an error in a user configuration file, the best solution may be to delete it and start over with the settings dialog.

If IDLE quits with no message, and it was not started from a console, try starting it from a console or terminal ( python -m idlelib ) and see if this results in an error message.

On Unix-based systems with tcl/tk older than 8.6.11 (see About IDLE ) certain characters of certain fonts can cause a tk failure with a message to the terminal. This can happen either if one starts IDLE to edit a file with such a character or later when entering such a character. If one cannot upgrade tcl/tk, then re-configure IDLE to use a font that works better.

Running user code¶

With rare exceptions, the result of executing Python code with IDLE is intended to be the same as executing the same code by the default method, directly with Python in a text-mode system console or terminal window. However, the different interface and operation occasionally affect visible results. For instance, sys.modules starts with more entries, and threading.active_count() returns 2 instead of 1.

By default, IDLE runs user code in a separate OS process rather than in the user interface process that runs the shell and editor. In the execution process, it replaces sys.stdin , sys.stdout , and sys.stderr with objects that get input from and send output to the Shell window. The original values stored in sys.__stdin__ , sys.__stdout__ , and sys.__stderr__ are not touched, but may be None .

Sending print output from one process to a text widget in another is slower than printing to a system terminal in the same process. This has the most effect when printing multiple arguments, as the string for each argument, each separator, the newline are sent separately. For development, this is usually not a problem, but if one wants to print faster in IDLE, format and join together everything one wants displayed together and then print a single string. Both format strings and str.join() can help combine fields and lines.

IDLE’s standard stream replacements are not inherited by subprocesses created in the execution process, whether directly by user code or by modules such as multiprocessing. If such subprocess use input from sys.stdin or print or write to sys.stdout or sys.stderr, IDLE should be started in a command line window. (On Windows, use python or py rather than pythonw or pyw .) The secondary subprocess will then be attached to that window for input and output.

If sys is reset by user code, such as with importlib.reload(sys) , IDLE’s changes are lost and input from the keyboard and output to the screen will not work correctly.

When Shell has the focus, it controls the keyboard and screen. This is normally transparent, but functions that directly access the keyboard and screen will not work. These include system-specific functions that determine whether a key has been pressed and if so, which.

The IDLE code running in the execution process adds frames to the call stack that would not be there otherwise. IDLE wraps sys.getrecursionlimit and sys.setrecursionlimit to reduce the effect of the additional stack frames.

When user code raises SystemExit either directly or by calling sys.exit, IDLE returns to a Shell prompt instead of exiting.

User output in Shell¶

When a program outputs text, the result is determined by the corresponding output device. When IDLE executes user code, sys.stdout and sys.stderr are connected to the display area of IDLE’s Shell. Some of its features are inherited from the underlying Tk Text widget. Others are programmed additions. Where it matters, Shell is designed for development rather than production runs.

For instance, Shell never throws away output. A program that sends unlimited output to Shell will eventually fill memory, resulting in a memory error. In contrast, some system text windows only keep the last n lines of output. A Windows console, for instance, keeps a user-settable 1 to 9999 lines, with 300 the default.

A Tk Text widget, and hence IDLE’s Shell, displays characters (codepoints) in the BMP (Basic Multilingual Plane) subset of Unicode. Which characters are displayed with a proper glyph and which with a replacement box depends on the operating system and installed fonts. Tab characters cause the following text to begin after the next tab stop. (They occur every 8 ‘characters’). Newline characters cause following text to appear on a new line. Other control characters are ignored or displayed as a space, box, or something else, depending on the operating system and font. (Moving the text cursor through such output with arrow keys may exhibit some surprising spacing behavior.)

The repr function is used for interactive echo of expression values. It returns an altered version of the input string in which control codes, some BMP codepoints, and all non-BMP codepoints are replaced with escape codes. As demonstrated above, it allows one to identify the characters in a string, regardless of how they are displayed.

Normal and error output are generally kept separate (on separate lines) from code input and each other. They each get different highlight colors.

For SyntaxError tracebacks, the normal ‘^’ marking where the error was detected is replaced by coloring the text with an error highlight. When code run from a file causes other exceptions, one may right click on a traceback line to jump to the corresponding line in an IDLE editor. The file will be opened if necessary.

Shell has a special facility for squeezing output lines down to a ‘Squeezed text’ label. This is done automatically for output over N lines (N = 50 by default). N can be changed in the PyShell section of the General page of the Settings dialog. Output with fewer lines can be squeezed by right clicking on the output. This can be useful lines long enough to slow down scrolling.

Squeezed output is expanded in place by double-clicking the label. It can also be sent to the clipboard or a separate view window by right-clicking the label.

Developing tkinter applications¶

IDLE is intentionally different from standard Python in order to facilitate development of tkinter programs. Enter import tkinter as tk; root = tk.Tk() in standard Python and nothing appears. Enter the same in IDLE and a tk window appears. In standard Python, one must also enter root.update() to see the window. IDLE does the equivalent in the background, about 20 times a second, which is about every 50 milliseconds. Next enter b = tk.Button(root, text=’button’); b.pack() . Again, nothing visibly changes in standard Python until one enters root.update() .

Most tkinter programs run root.mainloop() , which usually does not return until the tk app is destroyed. If the program is run with python -i or from an IDLE editor, a >>> shell prompt does not appear until mainloop() returns, at which time there is nothing left to interact with.

When running a tkinter program from an IDLE editor, one can comment out the mainloop call. One then gets a shell prompt immediately and can interact with the live application. One just has to remember to re-enable the mainloop call when running in standard Python.

Running without a subprocess¶

By default, IDLE executes user code in a separate subprocess via a socket, which uses the internal loopback interface. This connection is not externally visible and no data is sent to or received from the internet. If firewall software complains anyway, you can ignore it.

If the attempt to make the socket connection fails, Idle will notify you. Such failures are sometimes transient, but if persistent, the problem may be either a firewall blocking the connection or misconfiguration of a particular system. Until the problem is fixed, one can run Idle with the -n command line switch.

If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible.

Deprecated since version 3.4.

Help and Preferences¶

Help sources¶

Help menu entry “IDLE Help” displays a formatted html version of the IDLE chapter of the Library Reference. The result, in a read-only tkinter text window, is close to what one sees in a web browser. Navigate through the text with a mousewheel, the scrollbar, or up and down arrow keys held down. Or click the TOC (Table of Contents) button and select a section header in the opened box.

Help menu entry “Python Docs” opens the extensive sources of help, including tutorials, available at docs.python.org/x.y , where ‘x.y’ is the currently running Python version. If your system has an off-line copy of the docs (this may be an installation option), that will be opened instead.

Selected URLs can be added or removed from the help menu at any time using the General tab of the Configure IDLE dialog.

Setting preferences¶

The font preferences, highlighting, keys, and general preferences can be changed via Configure IDLE on the Option menu. Non-default user settings are saved in a .idlerc directory in the user’s home directory. Problems caused by bad user configuration files are solved by editing or deleting one or more of the files in .idlerc .

On the Font tab, see the text sample for the effect of font face and size on multiple characters in multiple languages. Edit the sample to add other characters of personal interest. Use the sample to select monospaced fonts. If particular characters have problems in Shell or an editor, add them to the top of the sample and try changing first size and then font.

On the Highlights and Keys tab, select a built-in or custom color theme and key set. To use a newer built-in color theme or key set with older IDLEs, save it as a new custom theme or key set and it well be accessible to older IDLEs.

IDLE on macOS¶

Under System Preferences: Dock, one can set “Prefer tabs when opening documents” to “Always”. This setting is not compatible with the tk/tkinter GUI framework used by IDLE, and it breaks a few IDLE features.

Extensions¶

IDLE contains an extension facility. Preferences for extensions can be changed with the Extensions tab of the preferences dialog. See the beginning of config-extensions.def in the idlelib directory for further information. The only current default extension is zzdummy, an example also used for testing.

idlelib¶

Source code: Lib/idlelib

The Lib/idlelib package implements the IDLE application. See the rest of this page for how to use IDLE.

Getting Started With Python IDLE

If you’ve recently downloaded Python onto your computer, then you may have noticed a new program on your machine called IDLE. You might be wondering, “What is this program doing on my computer? I didn’t download that!” While you may not have downloaded this program on your own, IDLE comes bundled with every Python installation. It’s there to help you get started with the language right out of the box. In this tutorial, you’ll learn how to work in Python IDLE and a few cool tricks you can use on your Python journey!

In this tutorial, you’ll learn:

  • What Python IDLE is
  • How to interact with Python directly using IDLE
  • How to edit, execute, and debug Python files with IDLE
  • How to customize Python IDLE to your liking

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

What Is Python IDLE?

Every Python installation comes with an Integrated Development and Learning Environment, which you’ll see shortened to IDLE or even IDE. These are a class of applications that help you write code more efficiently. While there are many IDEs for you to choose from, Python IDLE is very bare-bones, which makes it the perfect tool for a beginning programmer.

Python IDLE comes included in Python installations on Windows and Mac. If you’re a Linux user, then you should be able to find and download Python IDLE using your package manager. Once you’ve installed it, you can then use Python IDLE as an interactive interpreter or as a file editor.

An Interactive Interpreter

The best place to experiment with Python code is in the interactive interpreter, otherwise known as a shell. The shell is a basic Read-Eval-Print Loop (REPL). It reads a Python statement, evaluates the result of that statement, and then prints the result on the screen. Then, it loops back to read the next statement.

Note: For a full guide to the standard Python REPL, check out The Python Standard REPL: Try Out Code and Ideas Quickly.

The Python shell is an excellent place to experiment with small code snippets. You can access it through the terminal or command line app on your machine. You can simplify your workflow with Python IDLE, which will immediately start a Python shell when you open it.

A File Editor

Every programmer needs to be able to edit and save text files. Python programs are files with the .py extension that contain lines of Python code. Python IDLE gives you the ability to create and edit these files with ease.

Python IDLE also provides several useful features that you’ll see in professional IDEs, like basic syntax highlighting, code completion, and auto-indentation. Professional IDEs are more robust pieces of software and they have a steep learning curve. If you’re just beginning your Python programming journey, then Python IDLE is a great alternative!

How to Use the Python IDLE Shell

The shell is the default mode of operation for Python IDLE. When you click on the icon to open the program, the shell is the first thing that you see:

Blank Python Interpreter in IDLE

This is a blank Python interpreter window. You can use it to start interacting with Python immediately. You can test it out with a short line of code:

Hello World program shown in the IDLE python interpreter

Here, you used print() to output the string «Hello, from IDLE!» to your screen. This is the most basic way to interact with Python IDLE. You type in commands one at a time and Python responds with the result of each command.

Next, take a look at the menu bar. You’ll see a few options for using the shell:

the menu bar for IDLE with the Shell menu brought up showing the options of view last restart, restart shell, and interrupt execution

You can restart the shell from this menu. If you select that option, then you’ll clear the state of the shell. It will act as though you’ve started a fresh instance of Python IDLE. The shell will forget about everything from its previous state:

The result of executing some code in the IDLE shell, and then restarting the shell. The shell no longer knows about anything that happening in its previous state.

In the image above, you first declare a variable, x = 5 . When you call print(x) , the shell shows the correct output, which is the number 5 . However, when you restart the shell and try to call print(x) again, you can see that the shell prints a traceback. This is an error message that says the variable x is not defined. The shell has forgotten about everything that came before it was restarted.

You can also interrupt the execution of the shell from this menu. This will stop any program or statement that’s running in the shell at the time of interruption. Take a look at what happens when you send a keyboard interrupt to the shell:

Sending a keyboard interrupt with the Interrupt Execution option in the IDLE menu bar will result in something similar to this. The execution of this program was halted when that option was selected.

A KeyboardInterrupt error message is displayed in red text at the bottom of your window. The program received the interrupt and has stopped executing.

How to Work With Python Files

Python IDLE offers a full-fledged file editor, which gives you the ability to write and execute Python programs from within this program. The built-in file editor also includes several features, like code completion and automatic indentation, that will speed up your coding workflow. First, let’s take a look at how to write and execute programs in Python IDLE.

Opening a File

To start a new Python file, select File → New File from the menu bar. This will open a blank file in the editor, like this:

shows the blank file after opening a new file for editing in IDLE

From this window, you can write a brand new Python file. You can also open an existing Python file by selecting File → Open… in the menu bar. This will bring up your operating system’s file browser. Then, you can find the Python file you want to open.

If you’re interested in reading the source code for a Python module, then you can select File → Path Browser. This will let you view the modules that Python IDLE can see. When you double click on one, the file editor will open up and you’ll be able to read it.

The content of this window will be the same as the paths that are returned when you call sys.path . If you know the name of a specific module you want to view, then you can select File → Module Browser and type in the name of the module in the box that appears.

Editing a File

Once you’ve opened a file in Python IDLE, you can then make changes to it. When you’re ready to edit a file, you’ll see something like this:

an opened python file in IDLE containing a single line of code

The contents of your file are displayed in the open window. The bar along the top of the window contains three pieces of important information:

  1. The name of the file that you’re editing
  2. The full path to the folder where you can find this file on your computer
  3. The version of Python that IDLE is using

In the image above, you’re editing the file myFile.py , which is located in the Documents folder. The Python version is 3.7.1, which you can see in parentheses.

There are also two numbers in the bottom right corner of the window:

  1. Ln: shows the line number that your cursor is on.
  2. Col: shows the column number that your cursor is on.

It’s useful to see these numbers so that you can find errors more quickly. They also help you make sure that you’re staying within a certain line width.

There are a few visual cues in this window that will help you remember to save your work. If you look closely, then you’ll see that Python IDLE uses asterisks to let you know that your file has unsaved changes:

shows what an unsaved file looks like in the idle editor

The file name shown in the top of the IDLE window is surrounded by asterisks. This means that there are unsaved changes in your editor. You can save these changes with your system’s standard keyboard shortcut, or you can select File → Save from the menu bar. Make sure that you save your file with the .py extension so that syntax highlighting will be enabled.

Executing a File

When you want to execute a file that you’ve created in IDLE, you should first make sure that it’s saved. Remember, you can see if your file is properly saved by looking for asterisks around the filename at the top of the file editor window. Don’t worry if you forget, though! Python IDLE will remind you to save whenever you attempt to execute an unsaved file.

To execute a file in IDLE, simply press the F5 key on your keyboard. You can also select Run → Run Module from the menu bar. Either option will restart the Python interpreter and then run the code that you’ve written with a fresh interpreter. The process is the same as when you run python3 -i [filename] in your terminal.

When your code is done executing, the interpreter will know everything about your code, including any global variables, functions, and classes. This makes Python IDLE a great place to inspect your data if something goes wrong. If you ever need to interrupt the execution of your program, then you can press Ctrl + C in the interpreter that’s running your code.

How to Improve Your Workflow

Now that you’ve seen how to write, edit, and execute files in Python IDLE, it’s time to speed up your workflow! The Python IDLE editor offers a few features that you’ll see in most professional IDEs to help you code faster. These features include automatic indentation, code completion and call tips, and code context.

Automatic Indentation

IDLE will automatically indent your code when it needs to start a new block. This usually happens after you type a colon ( : ). When you hit the enter key after the colon, your cursor will automatically move over a certain number of spaces and begin a new code block.

You can configure how many spaces the cursor will move in the settings, but the default is the standard four spaces. The developers of Python agreed on a standard style for well-written Python code, and this includes rules on indentation, whitespace, and more. This standard style was formalized and is now known as PEP 8. To learn more about it, check out How to Write Beautiful Python Code With PEP 8.

Code Completion and Call Tips

When you’re writing code for a large project or a complicated problem, you can spend a lot of time just typing out all of the code you need. Code completion helps you save typing time by trying to finish your code for you. Python IDLE has basic code completion functionality. It can only autocomplete the names of functions and classes. To use autocompletion in the editor, just press the tab key after a sequence of text.

Python IDLE will also provide call tips. A call tip is like a hint for a certain part of your code to help you remember what that element needs. After you type the left parenthesis to begin a function call, a call tip will appear if you don’t type anything for a few seconds. For example, if you can’t quite remember how to append to a list, then you can pause after the opening parenthesis to bring up the call tip:

displays a simple call tip for the append method with a python list

The call tip will display as a popup note, reminding you how to append to a list. Call tips like these provide useful information as you’re writing code.

Code Context

The code context functionality is a neat feature of the Python IDLE file editor. It will show you the scope of a function, class, loop, or other construct. This is particularly useful when you’re scrolling through a lengthy file and need to keep track of where you are while reviewing code in the editor.

To turn it on, select Options → Code Context in the menu bar. You’ll see a gray bar appear at the top of the editor window:

shows the code context feature of the idle editor

As you scroll down through your code, the context that contains each line of code will stay inside of this gray bar. This means that the print() functions you see in the image above are a part of a main function. When you reach a line that’s outside the scope of this function, the bar will disappear.

How to Debug in IDLE

A bug is an unexpected problem in your program. They can appear in many forms, and some are more difficult to fix than others. Some bugs are tricky enough that you won’t be able to catch them by just reading through your program. Luckily, Python IDLE provides some basic tools that will help you debug your programs with ease!

Interpreter DEBUG Mode

If you want to run your code with the built-in debugger, then you’ll need to turn this feature on. To do so, select Debug → Debugger from the Python IDLE menu bar. In the interpreter, you should see [DEBUG ON] appear just before the prompt ( >>> ), which means the interpreter is ready and waiting.

When you execute your Python file, the debugger window will appear:

shows a blank debugger window in python idle

In this window, you can inspect the values of your local and global variables as your code executes. This gives you insight into how your data is being manipulated as your code runs.

You can also click the following buttons to move through your code:

  • Go: Press this to advance execution to the next breakpoint. You’ll learn about these in the next section.
  • Step: Press this to execute the current line and go to the next one.
  • Over: If the current line of code contains a function call, then press this to step over that function. In other words, execute that function and go to the next line, but don’t pause while executing the function (unless there is a breakpoint).
  • Out: If the current line of code is in a function, then press this to step out of this function. In other words, continue the execution of this function until you return from it.

Be careful, because there is no reverse button! You can only step forward in time through your program’s execution.

You’ll also see four checkboxes in the debug window:

  1. Globals: your program’s global information
  2. Locals: your program’s local information during execution
  3. Stack: the functions that run during execution
  4. Source: your file in the IDLE editor

When you select one of these, you’ll see the relevant information in your debug window.

Breakpoints

A breakpoint is a line of code that you’ve identified as a place where the interpreter should pause while running your code. They will only work when DEBUG mode is turned on, so make sure that you’ve done that first.

To set a breakpoint, right-click on the line of code that you wish to pause. This will highlight the line of code in yellow as a visual indication of a set breakpoint. You can set as many breakpoints in your code as you like. To undo a breakpoint, right-click the same line again and select Clear Breakpoint.

Once you’ve set your breakpoints and turned on DEBUG mode, you can run your code as you would normally. The debugger window will pop up, and you can start stepping through your code manually.

Errors and Exceptions

When you see an error reported to you in the interpreter, Python IDLE lets you jump right to the offending file or line from the menu bar. All you have to do is highlight the reported line number or file name with your cursor and select Debug → Go to file/line from the menu bar. This is will open up the offending file and take you to the line that contains the error. This feature works regardless of whether or not DEBUG mode is turned on.

Python IDLE also provides a tool called a stack viewer. You can access it under the Debug option in the menu bar. This tool will show you the traceback of an error as it appears on the stack of the last error or exception that Python IDLE encountered while running your code. When an unexpected or interesting error occurs, you might find it helpful to take a look at the stack. Otherwise, this feature can be difficult to parse and likely won’t be useful to you unless you’re writing very complicated code.

How to Customize Python IDLE

There are many ways that you can give Python IDLE a visual style that suits you. The default look and feel is based on the colors in the Python logo. If you don’t like how anything looks, then you can almost always change it.

To access the customization window, select Options → Configure IDLE from the menu bar. To preview the result of a change you want to make, press Apply. When you’re done customizing Python IDLE, press OK to save all of your changes. If you don’t want to save your changes, then simply press Cancel.

There are 5 areas of Python IDLE that you can customize:

  1. Fonts/Tabs
  2. Highlights
  3. Keys
  4. General
  5. Extensions

Let’s take a look at each of them now.

Fonts/Tabs

The first tab allows you to change things like font color, font size, and font style. You can change the font to almost any style you like, depending on what’s available for your operating system. The font settings window looks like this:

the font settings window of the idle customization pane

You can use the scrolling window to select which font you prefer. (I recommend you select a fixed-width font like Courier New.) Pick a font size that’s large enough for you to see well. You can also click the checkbox next to Bold to toggle whether or not all text appears in bold.

This window will also let you change how many spaces are used for each indentation level. By default, this will be set to the PEP 8 standard of four spaces. You can change this to make the width of your code more or less spread out to your liking.

Highlights

The second customization tab will let you change highlights. Syntax highlighting is an important feature of any IDE that highlights the syntax of the language that you’re working in. This helps you visually distinguish between the different Python constructs and the data used in your code.

Python IDLE allows you to fully customize the appearance of your Python code. It comes pre-installed with three different highlight themes:

  1. IDLE Day
  2. IDLE Night
  3. IDLE New

You can select from these pre-installed themes or create your own custom theme right in this window:

shows the syntax highlighting customization pane

Unfortunately, IDLE does not allow you to install custom themes from a file. You have to create customs theme from this window. To do so, you can simply start changing the colors for different items. Select an item, and then press Choose color for. You’ll be brought to a color picker, where you can select the exact color that you want to use.

You’ll then be prompted to save this theme as a new custom theme, and you can enter a name of your choosing. You can then continue changing the colors of different items if you’d like. Remember to press Apply to see your changes in action!

The third customization tab lets you map different key presses to actions, also known as keyboard shortcuts. These are a vital component of your productivity whenever you use an IDE. You can either come up with your own keyboard shortcuts, or you can use the ones that come with IDLE. The pre-installed shortcuts are a good place to start:

python idle settings keyboard shortcut customization pane

The keyboard shortcuts are listed in alphabetical order by action. They’re listed in the format Action — Shortcut, where Action is what will happen when you press the key combination in Shortcut. If you want to use a built-in key set, then select a mapping that matches your operating system. Pay close attention to the different keys and make sure your keyboard has them!

Creating Your Own Shortcuts

The customization of the keyboard shortcuts is very similar to the customization of syntax highlighting colors. Unfortunately, IDLE does not allow you to install custom keyboard shortcuts from a file. You must create a custom set of shortcuts from the Keys tab.

Select one pair from the list and press Get New Keys for Selection. A new window will pop up:

idle settings new keys popup window

Here, you can use the checkboxes and scrolling menu to select the combination of keys that you want to use for this shortcut. You can select Advanced Key Binding Entry >> to manually type in a command. Note that this cannot pick up the keys you press. You have to literally type in the command as you see it displayed to you in the list of shortcuts.

General

The fourth tab of the customization window is a place for small, general changes. The general settings tab looks like this:

shows teh general settings available for idle

Here, you can customize things like the window size and whether the shell or the file editor opens first when you start Python IDLE. Most of the things in this window are not that exciting to change, so you probably won’t need to fiddle with them much.

Extensions

The fifth tab of the customization window lets you add extensions to Python IDLE. Extensions allow you to add new, awesome features to the editor and the interpreter window. You can download them from the internet and install them to right into Python IDLE.

To view what extensions are installed, select Options → Configure IDLE -> Extensions. There are many extensions available on the internet for you to read more about. Find the ones you like and add them to Python IDLE!

Conclusion

In this tutorial, you’ve learned all the basics of using IDLE to write Python programs. You know what Python IDLE is and how you can use it to interact with Python directly. You’ve also learned how to work with Python files and customize Python IDLE to your liking.

You’ve learned how to:

  • Work with the Python IDLE shell
  • Use Python IDLE as a file editor
  • Improve your workflow with features to help you code faster
  • Debug your code and view errors and exceptions
  • Customize Python IDLE to your liking

Now you’re armed with a new tool that will let you productively write Pythonic code and save you countless hours down the road. Happy programming!

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Starting With Python IDLE

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Michael Neary

Michael is an avid Pythonista and writes for Real Python.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Dan Bader

Jaya Zhané

Mike Driscoll

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Learn Python IDLE for writing and executing codes | aipython

Aipython India

IDLE comes with python installation and it is used for writing python codes. The first thing anyone wants to do after installing Python on your machine is to write the first python code. To write a piece of code (sometimes also called script), you need IDE ( Integrated Development Environment) or an editor. An IDE is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build tools (optional), compiler/Interpreter and a debugger. Source code editor (or simply an editor) is a place where you can write code as well customize the code’s appearance (colour, font, highlights etc..). Once the script is written, it goes for a conversion from the source language (more often called High-level language) to machine code (low-level language).

Table of Contents

What is Python IDLE

Python default IDE is known as IDLE ( Integrated Development and Learning Environment). There is no need to install this IDE separately as it comes as default with Python installation. Although there are plenty of IDE which you can download separately on your system, still Python IDLE is considered as a super choice for a newbie. Python IDLE comes by default on Windows and Mac but Linux user has to download it using the package manager. You have learned to write a Python code in Interactive environment, where you get the instant result of an expression. Now it’s time to write a few lines of code to solve a problem. You can write multiple lines of code in the Interactive environment as well, but it is not favoured because of the debugging reasons.

IDLE features

  • coded in 100% pure Python, using the tkinter GUI toolkit
  • cross-platform: works mostly the same on Windows, Unix, and macOS
  • Python shell window (interactive interpreter) with colourizing of code input, output, and error messages
  • multi-window text editor with multiple undo, Python colourizing, smart indent, call tips, auto-completion, and other features
  • search within any window, replace within editor windows and search through multiple files (grep)
  • debugger with persistent breakpoints, stepping, and viewing of global and local namespaces
  • configuration, browsers, and other dialogs

Python IDLE components

On Windows, Python IDLE can be started by two methods

  1. Press Window button, a search box will appear, write idle and hit enter.
  2. Go to program list by pressing windows button and then look for Python in the program list. Expand the Python list by clicking on the down arrow and then click on IDLE (Python 3.x.y x64 bit) from the drop-down menu as shown in the image.

After opening, the Python IDLE window looks similar to the image shown below. The menu fields have been marked with red square boxes (in real the red square boxes are not present, this is done here for demonstration purpose only).

Now we see the various menu options present on Python IDLE. We have File, Edit, Shell, Debug, Options, window and help. When you click on any of the menus, you will see certain items in the drop-down list. I have tried to capture all the drop-down items of IDLE in the two images shown below.

Python IDLE to write code and execute it

Till now, you have seen various components of a Python IDLE window. Don’t worry about knowing all the components, as we progress further through this article, you will get to know about them in details. At first, this IDLE will act as Interactive Python Interpreter, meaning as soon as you write certain expression/code after >>> (Tripple forward arrow), you will get the result in the next line itself. You can evaluate multiple expression one by one or you could also write multiple lines of script and evaluate them. However, writing multiple lines is not advisable here. You will see how to write multiple lines of code and execute them in one go, in a while. A sample screenshot is provided below to clear your doubts if any.

At the bottom right portion of the window (both IDLE window and Editor window), you will observe two symbols Ln and Col. This represents current line number (Ln) and column number (Col) of the cursor.

a) Create a new file

To write multiple lines of code, we need an editor. You can open an editor by navigating to File menu and select the new file from the drop-down list. Alternatively, you can use the shortcut command ( Crtl+N). This is Python default editor and we will write our programs in this editor. Image shown below illustrate the method to create a new file for writing python program.

You have noticed that the name of the editor is untitled, which means the name has not been assigned to this file. We will first give a name and save the file. To do so, click on the file option of this editor (not the IDLE) and select Save from the drop-down list. It will ask for the location to save the file, browse the path where you want to save the file and provide a name with the extension .py with it and click on the Save button. You will notice the untiled is replaced with the name of your file along with the location. Now, we are good to go and write the program.

YouTube Video — https://www.youtu.be/aNcYbnZghHY

Write a short program (image is attached for the sample code) and click on the Save button from the file menu, alternatively press Ctrl+S to save the file. I have created two variables, added them and printed the results.

Note: You will observe an asterisk symbol(*) until you save the code. This symbol will disappear after saving the code.

You can execute the program by navigating to Run menu of this editor and select Run Module from the drop-down list. The keyboard shortcut to run the program is F5. After you hit F5 or Click on Run module, the editor window will be minimised and results will be displayed back in the IDLE window (main window). Find the image below to understand it.

b) Open an existing file

To open an existing file, navigate to File menu of any window (either the IDLE window or editor window) and select Open from the drop-down list. It will open a new window and ask you to choose a file. Browse the file location, select the file and click on Open button, the new file will be opened.

Once the file is opened, you can execute the program or make some changes to it. To execute the code use the same method as described earlier i.e. press F5. You can also modify/add the existing code and run again.

Improving work-flow

Till now you have understood how to use IDLE to write and execute python code. Now it’s time to increase your efficiency while writing code by utilizing IDLE tool features. Python IDLE provides you with three amazing features, which you can use, to implement your code faster and with ease. You are going to learn about

a) Automatic Indentation

Python is a kind of program which enforces code readability and code structuring through Indentation. It is the blank spaces that are applied at the starting of the next immediate line which ends with a colon (:). Understand it in little easy way, when you create function, loops, or classes, it ends with a colon and when you press Enter key the cursor goes to a new line. Here, instead of the cursor being starting at extreme left, it starts after 4 blank space. This is done automatically by Python IDLE to save time in the overall development process. An example of automatic indentation for function, loop and class is shown in the image below.

b) Call Tips

There are thousands of function and methods present in Python language and it is hard to remember each of them, especially the arguments that can be passed during a method call. Call tips help the programmer by providing a hint as what elements are needed next. When you place a left parenthesis, the call tip will pop up automatically, within a few seconds of inactivity, to provide a hint to the user about that particular element. Call tip may not appear for a method which falls under some specific library, for call tip to appear you need to import that library. On Windows OS, you can see a call tip by pressing Ctrl+’\’ button.

c) Code Completion

Python IDLE has basic code completion functionality. This feature helps the user to save coding time by bringing automatic class and function names, that are declared previously in the program. This helps the user to save their time significantly in the overall development process for a comparatively larger program. To use autocompletion in the editor, just press the tab key after a sequence of text. Here, in the below image, I have created a function called my_user_dashboard(). Whenever I want to use this function, I can type in my and then press the Tab button on the keyword, it will automatically complete the full-text my_user_dashboard.

Debugging a Python code in IDLE

We debug our code to make it free from any existing Bugs (mistakes) as well monitor how the changes are happening. For example, we can monitor a variable from its value assignment to the final result. Python IDLE provides basic debugging features to debug your code. A bug could appear in many from and one is different from others. Sometimes it’s very difficult to find the reason for its existence. IDLE provides two types of Debug method,

a) Interpreter Debug Mode

Interpreter debug mode is switched OFF by default and it can be invoked (activated) by navigating to Debug menu in the IDLE window and selecting Debugger option from the drop-down list. Once the debugger is activated you will notice [Debug ON] text before >>> arrow mark in the IDLE window as well debug control window (shown in the image below)will pop up.

After the debugger is ON, you can select your program (File->Open->Select your file) and hit F5 to run. This will load the program location in IDLE and debugger is now active to execute the script.

You’ll also see four checkboxes in the debug window:

  1. Globals: your program’s global information
  2. Locals: your program’s local information during execution
  3. Stack: the functions that run during execution
  4. Source: your file in the IDLE editor

Click on the Go button. Image shown below shows the process flow.

You will observe various global and local variables along with their values. To deactivate Debugger just close the Debug Control window, after that you will also see [DEBUG OFF] before >>> symbol in the main window.

b) Breakpoint(s)

Editor windows also have breakpoint functions. Lines with a breakpoint set are specially marked. Breakpoints only affect when running under the debugger. To apply breakpoint or breakpoints(s) in the editor window, Right-click on the line and select set breakpoint. Two option appears in the Right-click pop up, which are

Set Breakpoint: Set a breakpoint on the current line.
Clear Breakpoint: Clear the breakpoint on that line.

Python Interpreter will pause at the line where the breakpoint is set.

Customizing or Styling Python IDLE

Customizing options provide a lot of choices to design IDLE components such as font, highlight, keyword, theme. To access the customization window, select Options → Configure IDLE from the menu bar. To preview the result of a change you want to make, press Apply. When you’re done customizing Python IDLE, press OK button to save all of your changes.

There are 5 tabs inside Configure IDLE windows and mostly people uses four tabs for the customization purpose. Tab list are,

Font/Tab have the option to customize font that you can apply for your code. Apply colour, size and font style. You can also customize the number of spaces when the Tab button is pressed on the keyboard.

Highlight enables users to visually distinguish between the different Python constructs and the data used in the code. You can set a specific colour to the code components such as variable, text, function, class, keywords etc.. You can choose themes as well as customize foreground and background colours. Find the image below to see options available in Font and Highlight tab.

Key tabs show a list of keyboard shortcuts that are pre-defined for a particular OS. You can either come up with your keyboard shortcuts, or you can use the ones that come with IDLE.

General tab allows users to customize things like the window size and whether the shell or the file editor opens first when you start Python IDLE. Most of the things in this window are not required to change. Find the image below which shows various options under Key and General tab.

Conclusion

In this tutorial, you have learned about IDLE, it features, components. Now, I am sure that you can use IDLE to write new python code or open an existing script and execute them. You have also learned how to improve your programming efficiency by leveraging inbuilt tool features such as automatic indentation, call tips and automatic code completion. Debugging code also made easy with Interpreter debugger as well as breakpoints. Finally, you have also learned to customize IDLE for the giving it a better visual look with the help of fonts, colour, size as well highlights.

So, its time to practice your code on Python IDLE and I congratulate you in advance. Happy Learning !!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *