16. Додаток

16.1. Інтерактивний режим

There are two variants of the interactive REPL. The classic basic interpreter is supported on all platforms with minimal line control capabilities.

On Windows, or Unix-like systems with curses support, a new interactive shell is used by default. This one supports color, multiline editing, history browsing, and paste mode. To disable color, see Controlling color for details. Function keys provide some additional functionality. F1 enters the interactive help browser pydoc. F2 allows for browsing command-line history without output nor the >>> and prompts. F3 enters «paste mode», which makes pasting larger blocks of code easier. Press F3 to return to the regular prompt.

When using the new interactive shell, exit the shell by typing exit or quit. Adding call parentheses after those commands is not required.

If the new interactive shell is not desired, it can be disabled via the PYTHON_BASIC_REPL environment variable.

16.1.1. Обробка помилок

When an error occurs, the interpreter prints an error message and a stack trace. In interactive mode, it then returns to the primary prompt; when input came from a file, it exits with a nonzero exit status after printing the stack trace. (Exceptions handled by an except clause in a try statement are not errors in this context.) Some errors are unconditionally fatal and cause an exit with a nonzero exit status; this applies to internal inconsistencies and some cases of running out of memory. All error messages are written to the standard error stream; normal output from executed commands is written to standard output.

Введення символу переривання (зазвичай Control-C або Delete) у основному чи додатковому командному рядку скасовує введення та повертає до основного командного рядка. [1] Введення переривання під час виконання команди викликає виключення KeyboardInterrupt, яке може бути оброблено оператором try.

16.1.2. Виконувані скрипти Python

У BSD Unix системах скрипти Python можна зробити безпосередньо виконуваними, як скрипти оболонки, додавши рядок

#!/usr/bin/env python3

(за умови, що інтерпретатор знаходиться в змінній середовища користувача PATH) на початку сценарію та надає файлу режим виконання. #! має бути першими двома символами файлу. На деяких платформах цей перший рядок має закінчуватися закінченням рядка в стилі Unix ('\n'), а не закінченням рядка Windows ('\r\n'). Зауважте, що для початку коментаря в Python використовується хеш або символ фунта, '#'.

Скрипту можна надати режим виконання або дозвіл за допомогою команди chmod.

$ chmod +x myscript.py

У системах Windows немає поняття «виконуваний режим». Програма встановлення Python автоматично пов’язує файли .py з python.exe, щоб подвійне клацання файлу Python запускало його як програму. Розширення також може бути .pyw, у цьому випадку вікно консолі, яке в іншому випадку б з’явилось, приховується.

16.1.3. Інтерактивний файл запуску

Коли ви використовуєте Python в інтерактивному режимі, часто зручно мати деякі стандартні команди, які виконуються щоразу, коли запускається інтерпретатор. Ви можете зробити це, встановивши змінну середовища з назвою PYTHONSTARTUP на назву файлу, що містить ваші команди запуску. Це схоже на функцію .profile оболонок Unix.

Цей файл читається лише під час інтерактивних сеансів, а не тоді, коли Python читає команди зі сценарію, і не коли /dev/tty вказано як явне джерело команд (що інакше поводиться як інтерактивний сеанс). Він виконується в тому самому просторі імен, де виконуються інтерактивні команди, тому об’єкти, які він визначає або імпортує, можна використовувати без застережень в інтерактивному сеансі. Ви також можете змінити підказки sys.ps1 і sys.ps2 у цьому файлі.

Якщо ви хочете прочитати додатковий файл запуску з поточного каталогу, ви можете запрограмувати це в глобальному файлі запуску за допомогою коду на кшталт if os.path.isfile('.pythonrc.py'): exec(open ('.pythonrc.py').read()). Якщо ви хочете використовувати файл запуску в сценарії, ви повинні зробити це явно в сценарії:

import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    with open(filename) as fobj:
        startup_file = fobj.read()
    exec(startup_file)

16.1.4. Модулі налаштування

Python provides two hooks to let you customize it: sitecustomize and usercustomize. To see how it works, you need first to find the location of your user site-packages directory. Start Python and run this code:

>>> import site
>>> site.getusersitepackages()
'/home/user/.local/lib/python3.x/site-packages'

Тепер ви можете створити файл із назвою usercustomize.py у цьому каталозі та помістити в нього все, що завгодно. Це впливатиме на кожен виклик Python, якщо його не запущено з параметром -s для вимкнення автоматичного імпорту.

sitecustomize works in the same way, but is typically created by an administrator of the computer in the global site-packages directory, and is imported before usercustomize. See the documentation of the site module for more details.

Виноски