# The Interpreter (Command Line Console)
If the help function is called in the console without any arguments, Python presents an interactive help console, where you can find out about Python modules, symbols, keywords and more.
# Referring to the last expression
To get the value of the last result from your last expression in the console, use an underscore _ .
This magic underscore value is only updated when using a python expression that results in a value. Defining functions or for loops does not change the value. If the expression raises an exception there will be no changes to _ .
Remember, this magic variable is only available in the interactive python interpreter. Running scripts will not do this.
# Opening the Python console
The console for the primary version of Python can usually be opened by typing py into your windows console or python on other platforms.
If you have multiple versions, then by default their executables will be mapped to python2 or python3 respectively.
This of course depends on the Python executables being in your PATH.
# The PYTHONSTARTUP variable
You can set an environment variable called PYTHONSTARTUP for Python’s console. Whenever you enter the Python console, this file will be executed, allowing for you to add extra functionality to the console such as importing commonly-used modules automatically.
If the PYTHONSTARTUP variable was set to the location of a file containing this:
Then opening the Python console would result in this extra output:
# Command line arguments
Python has a variety of command-line switches which can be passed to py . These can be found by performing py —help , which gives this output on Python 3.4:
# Getting help about an object
The Python console adds a new function, help , which can be used to get information about a function or object.
For a function, help prints its signature (arguments) and its docstring, if the function has one.
For an object, help lists the object’s docstring and the different member functions which the object has.
1. Командная строка и окружение¶
Интерпретатор CPython просматривает командную строку и окружение для различных параметров настройки.
Детали реализации CPython: Схемы командной строки других реализаций могут отличаться. Дополнительные ресурсы см. в разделе Альтернативные реализации .
1.1. Командная строка¶
При вызове Python можно указать любой из этих параметров:
Самый распространенный вариант использования — это, конечно, простой вызов сценария:
1.1.1. Интерфейсные опции¶
Интерфейс интерпретатора напоминает шелл интерфейс UNIX, но предоставляет некоторые дополнительный методы вызова:
- При вызове со стандартным входом, подключенным к устройству tty, он запрашивает команды и выполняет их до тех пор, пока не будет прочитан EOF (символ конца файла, который можно создать с помощью Ctrl-D в UNIX или Ctrl-Z, Enter в Windows).
- При вызове с аргументом имени файла или с файлом в качестве стандартного ввода он считывает и выполняет сценарий из этого файла.
- При вызове с аргументом имени каталога он считывает и выполняет сценарий с соответствующим именем из этого каталога.
- При вызове с помощью -c command он выполняет оператор(ы) Python, заданные как command. Здесь command может содержать несколько операторов, разделенных новыми строками. Ведущий пробел важен в Python операторах!
- При вызове с -m module-name модуль выполняется как сценарий, при условии что он доступен.
В неинтерактивном режиме весь ввод анализируется перед его выполнением.
Параметр интерфейса завершает список опций, используемых интерпретатором, все последовательные аргументы заканчиваются на sys.argv . Обратите внимание, что первый элемент — нижний нулевой индекс ( sys.argv[0] ), является строкой, отражающей источник программы.
Выполнить команду Python кода в command. command может быть одним или несколькими операторами, разделенными новыми строками, с важным начальным пробелом, как в обычном модуле кода.
Если параметр задан, первый элемент sys.argv будет «-c» , а текущий каталог будет добавлен к началу sys.path (что позволит импортировать модули в этот каталог как модули верхнего уровня).
Вызывает событие аудита cpython.run_command с аргументом command .
Ищет в sys.path вызываемый модуль и выполняет его содержание как модуль __main__ .
Т. к. аргумент — имя module, вы не должны передавать расширение файла ( .py ). Имя модуля должно быть действительным абсолютным именем модуля Python, но реализация может не всегда воплотить это в жизнь (например, она может позволить вам использовать имя, которое включает дефис).
Также разрешены имена пакетов (включая пакеты пространства имён). Когда имя пакета будет поставляться вместо нормального модуля, интерпретатор выполнит <pkg>.__main__ как главный модуль. Это поведение намеренно аналогично обработке каталогов и zipfiles, которые передаются интерпретатору в качестве аргумента сценария.
Этот параметр не может использоваться со встроенными модулями и модулями расширений, написанными на языке C, поскольку они не имеют файлов модулей Python. Однако это может использоваться для предварительно собранных модулей, даже если файл первоисточника не доступен.
Если опция задана, первым элементом sys.argv будет полный путь к файлу модуля (во время нахождения файла модуля первый элемент будет установлен в «-m» ). Как и в случае с опцией -c , текущий каталог будет добавлен к началу sys.path .
Выбор -I может использоваться, чтобы управлять сценарием в изолированном режиме, где sys.path не содержит ни текущего каталога, ни справочника site-packages пользователя. Все переменные среды PYTHON* также игнорируются.
Многие стандартные библиотечные модули содержат код, вызываемый при выполнении в качестве сценария. Примером может служить модуль timeit :
Вызывает событие аудита cpython.run_module с аргументом module-name .
runpy.run_module() Эквивалентные функциональные возможности, непосредственно доступные для Python кода
PEP 338 – выполнение модулей в виде сценариев
Изменено в версии 3.1: Укажите имя пакета для запуска подмодуля __main__ .
Изменено в версии 3.4: Поддерживаются также пакеты пространства имён
Считывание команд со стандартного ввода ( sys.stdin ). Если стандартный ввод является терминалом, то подразумевается -i .
Если этот параметр задан, первый элемент sys.argv будет «-» , а текущий каталог будет добавлен к началу sys.path .
Вызывает событие аудита cpython.run_stdin без аргументов.
Выполнить Python код, содержащийся в script, который должен быть путём файловой системы (абсолютным или относительным) со ссылкой на файл Python, каталог, содержащий файл __main__.py , или zipfile, содержащий файл __main__.py .
Если этот параметр задан, первым элементом sys.argv будет имя сценария, указанное в командной строке.
Если имя сценария ссылается непосредственно на файл Python, каталог, содержащий этот файл, добавляется к началу sys.path , и файл выполняется как модуль __main__ .
Если имя сценария ссылается на каталог или zipfile, имя сценария добавляется к началу sys.path , и файл __main__.py в этом расположении выполняется как модуль __main__ .
Опция -I может использоваться, чтобы управлять сценарием в изолированном режиме, где sys.path не содержит ни каталогов сценарных, ни каталога site-packages пользователя. Все переменные среды PYTHON* также игнорируются.
Вызывает событие аудита cpython.run_file с аргументом filename .
runpy.run_path() эквивалентные функциональные возможности, непосредственно доступные для Python кода
Если параметр интерфейса не задан, подразумевается -i , sys.argv[0] является пустой строкой ( «» ) и текущий каталог будет добавлен к началу sys.path . Кроме того, автоматически включаются функции автодополнения табов и редактирования истории, если они доступны на вашей платформе (см. Конфигурация Readline ).
Изменено в версии 3.4: Автоматическое включение автодополнения табов и редактирования истории.
1.1.2. Универсальные опции¶
Напечатать краткое описание всех параметров командной строки.
Напечатать номер версии Python и выйти. Примером вывода может быть:
При двойном вводе напечатает дополнительную информацию о сборке, например:
Добавлено в версии 3.6: Опция -VV .
1.1.3. Прочие опции¶
Выдать предупреждение при сравнении bytes или bytearray с str или bytes с int . Выдать ошибку, если опция задана дважды ( -bb ).
Изменено в версии 3.5: Влияет на сравнение bytes с int .
Если задано, Python не будет пытаться записать файлы .pyc при импорте исходных модулей. См. также раздел PYTHONDONTWRITEBYTECODE .
Управляет поведением проверки файлов .pyc на основе хэшей. См. инвалидацию кэша байткода . Если установлено значение default , проверенные и непроверенные файлы кэша байт-кода на основе хеша проверяются в соответствии с их семантикой по умолчанию. Если установлено значение always , все файлы .pyc на основе хэшей, независимо от того, отмечены они или нет, проверяются на соответствие их соответствующему исходному файлу. Если задано значение never , файлы .pyc на основе хэшей не проверяются на соответствие их соответствующим исходным файлам.
Этот параметр не влияет на семантику файлов .pyc на основе временных меток.
Включить отладочный вывод парсера (только для эксперта, в зависимости от вариантов компиляции). См. также раздел PYTHONDEBUG .
Игнорировать все переменные среды PYTHON* , например, PYTHONPATH и PYTHONHOME , которые могут быть установлены.
Когда сценарий передаётся в качестве первого аргумента или используется параметр -c , после выполнения сценария или команды, даже если sys.stdin не является терминалом, следует перейти в интерактивный режим. Файл PYTHONSTARTUP не считан.
Может быть полезно для проверки глобальных переменных или трассировки стека, когда сценарий вызывает исключение. См. также раздел PYTHONINSPECT .
Запустить Python в изолированном режиме. Также подразумевает -E и -s. В изолированном режиме sys.path не содержит ни каталог сценария, ни каталог site-packages пользователя. Все переменные среды PYTHON* также игнорируются. Дополнительные ограничения могут быть введены для предотвращения ввода пользователем вредоносного кода.
Добавлено в версии 3.4.
Удалить операторы assert и любой код, обусловленный значением __debug__ . Увеличить имя файла для скомпилированных ( байт-код ) файлов, добавив .opt-1 перед расширением .pyc (см. PEP 488). См. также PYTHONOPTIMIZE .
Изменено в версии 3.5: Изменены имена файлов .pyc согласно PEP 488.
Сделать -O , а также отбросить строки документации. Увеличить имя файла для скомпилированных ( байт-код ) файлов, добавив .opt-2 перед расширением .pyc (см. PEP 488).
Изменено в версии 3.5: Изменены имена файлов .pyc согласно PEP 488.
Не отображать сообщения об авторских правах и версии даже в интерактивном режиме.
Добавлено в версии 3.2.
Включить хеш-рандомизацию. Опция действует только в том случае, если для переменной среды PYTHONHASHSEED установлено значение 0 , поскольку по умолчанию хеш-рандомизация включена.
В предыдущих версиях Python этот параметр включает рандомизацию хеширования, так что значения __hash__() объектов str и bytes «засолены» непредсказуемым случайным значением. Хотя они остаются постоянными в рамках отдельного процесса Python, они не предсказуемы между повторными вызовами Python.
Рандомизация хеширования предназначена для обеспечения защиты от отказа в обслуживании, вызванного тщательно подобранными вводами, которые используют наихудшую производительность конструкции dict, сложность O(n^2). Дополнительные сведения см. на сайте.
PYTHONHASHSEED позволяет вам установить фиксированное значение для секретного хеш-кода.
Изменено в версии 3.7: Параметр больше не игнорируется.
Добавлено в версии 3.2.3.
PEP 370 – каталог site-packages для каждого пользователя
Отключить импорт модуля site и связанные с ним манипуляции с sys.path , зависящие от сайта. Также отключить эти манипуляции, если site будет явно импортирован позже (вызовите site.main() , если вам нужно чтобы они запускались).
Принудительно отключить буферизацию потоков stdout и stderr. Этот параметр не влияет на поток stdin.
Изменено в версии 3.7: Текстовый слой потоков stdout и stderr теперь не буферизован.
Печать сообщения при каждой инициализации модуля с указанием места (имени файла или встроенного модуля), откуда оно загружается. Дважды ( -vv ) распечатает сообщение для каждого файла, который проверяется при поиске модуля. Также содержит информацию о очистке модуля на выходе. См. также раздел PYTHONVERBOSE .
Управление предупреждением. Python механизм предупреждения по умолчанию печатает предупреждающие сообщения в sys.stderr . У типичного предупреждающего сообщения есть следующая форма:
По умолчанию каждое предупреждение печатается один раз для каждой исходной строки, где оно происходит. Этот параметр управляет частотой печати предупреждений.
Может быть указано несколько опций -W ; когда предупреждение соответствует более чем одному параметру, выполняется действие для последнего совпадающего параметра. Недопустимые параметры -W игнорируются (хотя при первом предупреждении печатается предупреждающее сообщение о недопустимых параметрах).
Предупреждениями также можно управлять с помощью переменной среды PYTHONWARNINGS и из программы Python с помощью модуля warnings .
В простейших настройках определенное действие безоговорочно применяется ко всем предупреждениям, выдаваемым процессом (даже к тем, которые по умолчанию игнорируются):
Имена действий могут быть сокращены по желанию (например, -Wi , -Wd , -Wa , -We ), и интерпретатор преобразует их в соответствующее имя действия.
Пропустить первую строку исходника, разрешив использование не Unix-форм #!cmd . Это предназначено только для хака DOS.
Зарезервирован для различных опций реализации. CPython в настоящее время определяет следующие возможные значения:
- -X faulthandler для включения faulthandler ;
- -X showrefcount для вывода общего счетчика ссылок и количества использованных блоков памяти при завершении программы или после каждого оператора в интерактивном интерпретаторе. Работает только в отладочных сборках.
- -X tracemalloc для начала отслеживание распределения памяти Python с помощью модуля tracemalloc . По умолчанию в traceback трассировки сохраняет только самый последний фрейм. Используйте -X tracemalloc=NFRAME , чтобы начать трассировку с пределом трассировки фреймов NFRAME. См. tracemalloc.start() для получения дополнительной информации.
- -X showalloccount для вывода общего количества выделенных объектов для каждого типа по завершении программы. Работает только, когда Python был собран с определённым COUNT_ALLOCS .
- -X importtime , чтобы показать, сколько времени занимает каждый импорт. Он показывает имя модуля, совокупное время (включая вложенный импорт) и собственное время (исключая вложенный импорт). Следует отметить, что его вывод может быть нарушен в многопоточном приложении. Типичное использование — python3 -X importtime -c ‘import asyncio’ . См. также раздел PYTHONPROFILEIMPORTTIME .
- -X dev : включить «режим разработки» CPython, введя дополнительные проверки среды выполнения, которые слишком дороги для включения по умолчанию. Он не должен быть более подробным, чем значение по умолчанию, если код является правильным: новые предупреждения выдаются только при обнаружении проблемы. Эффект от режима разработчика:
- Добавьте фильтр предупреждения default как -W default .
- Установить отладочные хуки на распределители памяти: см. C функцию PyMem_SetupDebugHooks() .
- Включить модуль faulthandler для сброса Python трейсбэка в случае сбоя.
- Включить asyncio режим отладки .
- Установить dev_mode атрибут sys.flags True . деструктор регистрирует исключения close() .
Также позволяет передавать произвольные значения и извлекать их через словарь sys._xoptions .
Изменено в версии 3.2: Добавлен параметр -X .
Добавлено в версии 3.3: Опция -X faulthandler .
Добавлено в версии 3.4: Параметры -X showrefcount и -X tracemalloc .
Добавлено в версии 3.6: Опция -X showalloccount .
Добавлено в версии 3.7: Опции -X importtime , -X dev и -X utf8 .
Добавлено в версии 3.8: Опция -X pycache_prefix . Опция -X dev теперь регистрирует исключения close() в деструкторе io.IOBase .
1.1.4. Опции, которые вы не должны использовать¶
Зарезервировано для использования Jython.
1.2. Переменные окружения¶
Переменные среды влияют на поведение Python, они обрабатываются перед переключателями командной строки, отличными от -E или -I. Обычно переключатели командной строки переопределяют переменные среды в случае конфликта.
Изменить расположение стандартных библиотек Python. По умолчанию библиотеки ищутся в prefix /lib/python version и exec_prefix /lib/python version , где prefix и exec_prefix — это каталоги, зависящие от установки, оба по умолчанию — /usr/local .
Если для PYTHONHOME задан один каталог, его значение заменяет как prefix , так и exec_prefix . Чтобы указать для них разные значения, установить PYTHONHOME на prefix : exec_prefix .
Увеличить путь поиска по умолчанию для файлов модулей. Формат совпадает с форматом PATH оболочки: одно или несколько путей каталога, разделенных os.pathsep (например, двоеточия в Unix или точка с запятой в Windows). Несуществующие каталоги автоматически игнорируются.
В дополнение к обычным каталогам, отдельные записи PYTHONPATH могут относиться к zip-файлам, содержащим чистые модули Python (в исходной или скомпилированной форме). Модули расширений нельзя импортировать из zip-файлов.
Путь поиска по умолчанию зависит от установки, но обычно начинается с prefix /lib/python version (см. PYTHONHOME выше). Он всегда добавляется к PYTHONPATH .
Дополнительный каталог будет вставлен в путь поиска перед PYTHONPATH , как описано выше в разделе Интерфейсные опции . Путь поиска можно изменить из программы Python с помощью переменной sys.path .
Если это имя читаемого файла, команды Python в этом файле выполняются до отображения первого приглашения в интерактивном режиме. Файл выполняется в том же пространстве имён, в котором выполняются интерактивные команды, так что определенные или импортированные в нём объекты могут использоваться без квалификации в интерактивном сеансе. Вы также можете изменить подсказки sys.ps1 и sys.ps2 и хук sys.__interactivehook__ в этом файле.
Вызывает событие аудита cpython.run_startup с именем файла в качестве аргумента при запуске.
Если задана непустая строка, это эквивалентно указанию параметра -O . Если установлено целое число, это эквивалентно многократному указанию -O .
Если установлена, она именует вызываемый объект, используя нотацию пути с точками. Модуль, содержащий вызываемый объект, будет импортирован, а затем вызываемый объект будет запущен реализацией по умолчанию sys.breakpointhook() , которая сама вызывается встроенным breakpoint() . Если не задана или установлена пустая строка, она эквивалентен значению «pdb.set_trace». Установка значения в строку «0» приводит к тому, что реализация по умолчанию sys.breakpointhook() ничего не делает, кроме немедленного возврата.
Добавлено в версии 3.7.
Если для неё задана непустая строка, это эквивалентно указанию параметра -d . Если установлено целое число, это эквивалентно многократному указанию -d .
Если установлена в непустую строку, это эквивалентно определению опции -i .
Переменная также может быть изменена кодом Python с использованием os.environ для принудительного режима проверки при завершении программы.
Если для неё задана непустая строка, это эквивалентно указанию параметра -u .
Если для неё задана непустая строка, это эквивалентно указанию параметра -v . Если установлено целое число, это эквивалентно многократному указанию -v .
Если установлена, Python игнорирует регистр в операторах import . Это работает только в Windows и OS X.
Если для этого параметра установлена непустая строка, Python не будет пытаться записывать файлы .pyc при импорте исходных модулей. Это эквивалентно указанию параметра -B .
Если установлено, Python будет записывать файлы .pyc в зеркальном дереве каталогов по этому пути, а не в каталогах __pycache__ в исходном дереве. Это эквивалентно указанию опции -X pycache_prefix=PATH .
Добавлено в версии 3.8.
Если переменная не установлена или содержит значение random , для заполнения хэшей объектов str и bytes используется случайное значение.
Если для PYTHONHASHSEED задано целочисленное значение, оно используется в качестве фиксированного начального числа для генерации hash() типов, охватываемых рандомизацией хэша.
Её цель — разрешить повторяемое хеширование, например, для самотестирования самого интерпретатора, или позволить кластеру процессов Python совместно использовать хеш-значения.
Целое число должно быть десятичным числом в диапазоне [0,4294967295]. Указание значения 0 отключит рандомизацию хэша.
Добавлено в версии 3.2.3.
Если она установлена до запуска интерпретатора, то переопределяет кодировку, используемую в stdin/stdout/stderr, в синтаксисе encodingname:errorhandler . И encodingname , и :errorhandler не являются обязательными и содержат то же значение, что и str.encode() .
Для stderr часть :errorhandler игнорируется; обработчик всегда будет ‘backslashreplace’ .
Изменено в версии 3.4: Часть encodingname теперь не является обязательной.
Изменено в версии 3.6: Кодировка в Windows, указанная этой переменной, игнорируется для буферов интерактивной консоли, если также не указана PYTHONLEGACYWINDOWSSTDIO . Файлы и каналы, перенаправленные через стандартные потоки, не затрагиваются.
PEP 370 — каталог site-packages для каждого пользователя
PEP 370 — каталог site-packages для каждого пользователя
Если переменная среды установлена, для sys.argv[0] будет установлено её значение вместо значения, полученного через среду выполнения C. Работает только в Mac OS X.
Эквивалент опции -W . Если задана строка, разделенная запятыми, это эквивалентно многократному указанию -W , при этом фильтры, расположенные позже в списке, приоритетнее над фильтрами ранее в списке.
В простейших настройках определенное действие безоговорочно применяется ко всем предупреждениям, выдаваемым процессом (даже к тем, которые по умолчанию игнорируются):
Если для этой переменной среды задана непустая строка, при запуске вызывается faulthandler.enable() : установить обработчик для сигналов SIGSEGV , SIGFPE , SIGABRT , SIGBUS и SIGILL для дампа трассировки Python. Это эквивалентно опции -X faulthandler .
Добавлено в версии 3.3.
Если для этой переменной среды задана непустая строка, начинать отслеживать выделение памяти Python с помощью модуля tracemalloc . Значение переменной — это максимальное количество фреймов, сохраняемых в обратной трассировке trace. Например, PYTHONTRACEMALLOC=1 хранит только самый последний фрейм. См. tracemalloc.start() для получения дополнительной информации.
Добавлено в версии 3.4.
Если для переменной среды задана непустая строка, Python покажет, сколько времени занимает каждый импорт. Это в точности эквивалентно настройке -X importtime в командной строке.
Добавлено в версии 3.7.
Если для этой переменной среды задана непустая строка, включить режим отладки модуля asyncio .
Добавлено в версии 3.4.
Установить распределители памяти Python и/или установить отладочные хуки.
Установить семейство распределителей памяти, используемых Python:
- default : использовать распределители памяти по умолчанию .
- malloc : использовать функцию malloc() библиотеки C для всех доменов ( PYMEM_DOMAIN_RAW , PYMEM_DOMAIN_MEM , PYMEM_DOMAIN_OBJ ).
- pymalloc : использовать pymalloc распределитель для доменов PYMEM_DOMAIN_MEM и PYMEM_DOMAIN_OBJ и использовать функцию malloc() для домена PYMEM_DOMAIN_RAW .
Установить отладочные хуки:
- debug : установить хуки отладки поверх распределителей памяти по умолчанию .
- malloc_debug : то же, что и malloc , но с установкой отладочных хуков.
- pymalloc_debug : то же, что и pymalloc , но с установкой отладочных хуков.
См. распределителей памяти по умолчанию и функцию PyMem_SetupDebugHooks() (установить отладочные хуки на распределителях памяти Python).
Изменено в версии 3.7: Добавлен распределитель «default» .
Добавлено в версии 3.6.
Если установлена непустая строка, Python будет печатать статистику pymalloc распределителя памяти каждый раз, когда создаётся новая объектная арена pymalloc, а также при завершении работы.
Переменная игнорируется, если переменная среды PYTHONMALLOC используется для принудительного использования распределителя malloc() библиотеки C или если Python настроен без поддержки pymalloc .
Изменено в версии 3.6: Переменную теперь также можно использовать в Python, скомпилированном в режиме релиза. Теперь она не действует, если определена пустой строкой.
Если задана непустая строка, кодировка файловой системы по умолчанию и режим ошибок вернутся к своим значениям до 3.6 «mbcs» и «replace» соответственно. В противном случае используются новые значения по умолчанию «utf-8» и «surrogatepass».
Также можно включить во время выполнения с sys._enablelegacywindowsfsencoding() .
Добавлено в версии 3.6: См. PEP 529 для получения более подробной информации.
Если задана непустая строка, новые средства чтения и записи консоли не используются. Это означает, что Юникод символы будут кодироваться в соответствии с активной кодовой страницей консоли, а не с использованием utf-8.
Переменная игнорируется, если стандартные потоки перенаправляются (в файлы или каналы), а не ссылаются на буферы консоли.
Добавлено в версии 3.6.
Если установлено значение 0 , основное приложение командной строки Python пропускает приведение устаревших локалей C и POSIX на основе ASCII к более функциональной альтернативе на основе UTF-8.
Если переменная не установлена (или ей присвоено значение, отличное от 0 ), переменная среды переопределения локали LC_ALL также не устанавливается, а текущая локаль, указанная для категории LC_CTYPE , является либо локалью по умолчанию C , либо явно ASCII-основанной локали POSIX , то Python CLI попытается настроить следующие локали для категории LC_CTYPE в порядке, указанном перед загрузкой среды выполнения интерпретатора:
- C.UTF-8
- C.utf8
- UTF-8
Если установка одной из этих категорий локали прошла успешно, то переменная среды LC_CTYPE также будет соответственно установлена в текущей среде процесса перед инициализацией среды выполнения Python. Это гарантирует, что обновленный параметр будет виден как самому интерпретатору, так и другим компонентам, зависящим от локали, работающим в одном процессе (например, библиотеке GNU readline ), и в подпроцессах (независимо от того, являются ли эти процессы запущенными интерпретатором Python или нет), а также в операциях, которые запрашивают среду, а не текущую локаль C (например, собственная Python locale.getdefaultlocale() ).
Настройка одной из этих локалей (явно или через указанное выше неявное принуждение языковых стандартов) автоматически включает surrogateescape обработчик ошибки для sys.stdin и sys.stdout ( sys.stderr продолжает использовать backslashreplace , как и в любой другой локали). Это поведение обработки потока может быть изменено, как обычно, с помощью PYTHONIOENCODING .
Для целей отладки установка PYTHONCOERCECLOCALE=warn приведёт к тому, что Python будет выдавать предупреждающие сообщения на stderr , если либо активируется принуждение локали, либо если языковой стандарт, который мог бы вызвать приведение, всё ещё активен при инициализации среды выполнения Python.
Также обратите внимание, что даже если принуждение локали отключено или не удается найти подходящую целевую локаль, PYTHONUTF8 по-прежнему будет активироваться по умолчанию в устаревших языковых стандартах на основе ASCII. Обе функции должны быть отключены, чтобы интерпретатор использовал ASCII вместо UTF-8 для системных интерфейсов.
Добавлено в версии 3.7: См. PEP 538 для получения более подробной информации.
Если для этой переменной среды задана непустая строка, включается «режим разработки» CPython. См. опцию -X dev .
Добавлено в версии 3.7.
Если установлено значение 1 , включает режим интерпретатора UTF-8, где UTF-8 используется в качестве кодировки текста для системных интерфейсов, независимо от текущей настройки локали.
-
возвращает ‘UTF-8’ (кодировка локали игнорируется). возвращает ‘UTF-8’ (кодировка локали игнорируется, а параметр функции do_setlocale не действует). , sys.stdout и sys.stderr все используют UTF-8 в качестве кодировки текста, при этом surrogateescape обработчик ошибки включён для sys.stdin и sys.stdout ( sys.stderr продолжает использовать backslashreplace , как и в режиме с учётом локали по умолчанию)
Вследствие изменений в этих API нижнего уровня другие API более высокого уровня также демонстрируют другое поведение по умолчанию:
- Аргументы командной строки, переменные среды и имена файлов декодируются в текст с использованием кодировки UTF-8. и os.fsencode() используют кодировку UTF-8. , io.open() и codecs.open() по умолчанию используют кодировку UTF-8. Однако они по-прежнему используют строгий обработчик ошибок по умолчанию, так что попытка открыть двоичный файл в текстовом режиме может вызвать исключение, а не создавать бессмысленные данные.
Обратите внимание, что стандартные настройки потока в режиме UTF-8 могут быть отменены PYTHONIOENCODING (так же, как они могут быть в режиме с учётом локали по умолчанию).
Если установлено значение 0 , интерпретатор работает в режиме с учётом локали по умолчанию.
Установка любой другой непустой строки вызывает ошибку при инициализации интерпретатора.
Если переменная среды вообще не задана, то интерпретатор по умолчанию использует текущие настройки локали, если текущая локаль не определена как устаревшая локаль на основе ASCII (как описано для PYTHONCOERCECLOCALE ), и принуждение локали отключено или не работает. В таких устаревших региональных стандартах интерпретатор по умолчанию включает режим UTF-8, если явно не указано иное.
Также доступна как опция -X utf8 .
Добавлено в версии 3.7: См. PEP 540 для получения более подробной информации.
1.2.1. Переменные режима отладки¶
Установка этих переменных влияет только на отладочную сборку Python.
Если установлена, Python будет печатать отладочную информацию о потоках.
Нужен Python, настроенный с опцией сборки —with-pydebug .
Если установлено, Python будет сбрасывать объекты и счётчики ссылок, все ещё живые после завершения работы интерпретатора.
Python “-m” flag Example and How to Use It
The -m flag in Python stands for the “module name.” When you pass the -m flag followed by a module name to the Python interpreter, it will locate the module and execute its content as the __main__ module. This allows you to run a module directly from the command line.
If the -m flag is given to the Python statement, the first element of sys.argv will be the full path to the module file (while the module file is being found, the first item will be set to “-m”).
When -c is used with a statement on the command-line interface, it executes the Python statement(s) given as a command. When a package name is provided instead of a normal module, the interpreter will execute the .main as the main module.
When invoking Python, you may specify any of these options,
When you call a command with -m module-name, the given module is located on the Python module path and executed as a script.
If you regularly install new modules, you notice one thing: every time you write an install command, you must see the -m flag. So, what does the -m flag mean in the python -m pip install <package> command? Or upgrading pip using the python -m pip install –upgrade pip.
Here the command may include multiple statements separated by newlines. Leading whitespace is significant in Python statements!
1. Command line and environment¶
The CPython interpreter scans the command line and the environment for various settings.
CPython implementation detail: Other implementations’ command line schemes may differ. See Alternate Implementations for further resources.
1.1. Command line¶
When invoking Python, you may specify any of these options:
The most common use case is, of course, a simple invocation of a script:
1.1.1. Interface options¶
The interpreter interface resembles that of the UNIX shell, but provides some additional methods of invocation:
When called with standard input connected to a tty device, it prompts for commands and executes them until an EOF (an end-of-file character, you can produce that with Ctrl — D on UNIX or Ctrl — Z, Enter on Windows) is read.
When called with a file name argument or with a file as standard input, it reads and executes a script from that file.
When called with a directory name argument, it reads and executes an appropriately named script from that directory.
When called with -c command , it executes the Python statement(s) given as command. Here command may contain multiple statements separated by newlines. Leading whitespace is significant in Python statements!
When called with -m module-name , the given module is located on the Python module path and executed as a script.
In non-interactive mode, the entire input is parsed before it is executed.
An interface option terminates the list of options consumed by the interpreter, all consecutive arguments will end up in sys.argv – note that the first element, subscript zero ( sys.argv[0] ), is a string reflecting the program’s source.
Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code.
If this option is given, the first element of sys.argv will be "-c" and the current directory will be added to the start of sys.path (allowing modules in that directory to be imported as top level modules).
Raises an auditing event cpython.run_command with argument command .
Search sys.path for the named module and execute its contents as the __main__ module.
Since the argument is a module name, you must not give a file extension ( .py ). The module name should be a valid absolute Python module name, but the implementation may not always enforce this (e.g. it may allow you to use a name that includes a hyphen).
Package names (including namespace packages) are also permitted. When a package name is supplied instead of a normal module, the interpreter will execute <pkg>.__main__ as the main module. This behaviour is deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script argument.
This option cannot be used with built-in modules and extension modules written in C, since they do not have Python module files. However, it can still be used for precompiled modules, even if the original source file is not available.
If this option is given, the first element of sys.argv will be the full path to the module file (while the module file is being located, the first element will be set to "-m" ). As with the -c option, the current directory will be added to the start of sys.path .
-I option can be used to run the script in isolated mode where sys.path contains neither the current directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too.
Many standard library modules contain code that is invoked on their execution as a script. An example is the timeit module:
Raises an auditing event cpython.run_module with argument module-name .
Equivalent functionality directly available to Python code
PEP 338 – Executing modules as scripts
Changed in version 3.1: Supply the package name to run a __main__ submodule.
Changed in version 3.4: namespace packages are also supported
Read commands from standard input ( sys.stdin ). If standard input is a terminal, -i is implied.
If this option is given, the first element of sys.argv will be "-" and the current directory will be added to the start of sys.path .
Raises an auditing event cpython.run_stdin with no arguments.
Execute the Python code contained in script, which must be a filesystem path (absolute or relative) referring to either a Python file, a directory containing a __main__.py file, or a zipfile containing a __main__.py file.
If this option is given, the first element of sys.argv will be the script name as given on the command line.
If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path , and the file is executed as the __main__ module.
If the script name refers to a directory or zipfile, the script name is added to the start of sys.path and the __main__.py file in that location is executed as the __main__ module.
-I option can be used to run the script in isolated mode where sys.path contains neither the script’s directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too.
Raises an auditing event cpython.run_file with argument filename .
Equivalent functionality directly available to Python code
If no interface option is given, -i is implied, sys.argv[0] is an empty string ( "" ) and the current directory will be added to the start of sys.path . Also, tab-completion and history editing is automatically enabled, if available on your platform (see Readline configuration ).
Changed in version 3.4: Automatic enabling of tab-completion and history editing.
1.1.2. Generic options¶
Print a short description of all command line options and corresponding environment variables and exit.
Print a short description of Python-specific environment variables and exit.
New in version 3.11.
Print a description of implementation-specific -X options and exit.
New in version 3.11.
Print complete usage information and exit.
New in version 3.11.
Print the Python version number and exit. Example output could be:
When given twice, print more information about the build, like:
New in version 3.6: The -VV option.
1.1.3. Miscellaneous options¶
Issue a warning when comparing bytes or bytearray with str or bytes with int . Issue an error when the option is given twice ( -bb ).
Changed in version 3.5: Affects comparisons of bytes with int .
If given, Python won’t try to write .pyc files on the import of source modules. See also PYTHONDONTWRITEBYTECODE .
Control the validation behavior of hash-based .pyc files. See Cached bytecode invalidation . When set to default , checked and unchecked hash-based bytecode cache files are validated according to their default semantics. When set to always , all hash-based .pyc files, whether checked or unchecked, are validated against their corresponding source file. When set to never , hash-based .pyc files are not validated against their corresponding source files.
The semantics of timestamp-based .pyc files are unaffected by this option.
Turn on parser debugging output (for expert only, depending on compilation options). See also PYTHONDEBUG .
Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME , that might be set.
See also the -P and -I (isolated) options.
When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal. The PYTHONSTARTUP file is not read.
This can be useful to inspect global variables or a stack trace when a script raises an exception. See also PYTHONINSPECT .
Run Python in isolated mode. This also implies -E , -P and -s options.
In isolated mode sys.path contains neither the script’s directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too. Further restrictions may be imposed to prevent the user from injecting malicious code.
New in version 3.4.
Remove assert statements and any code conditional on the value of __debug__ . Augment the filename for compiled ( bytecode ) files by adding .opt-1 before the .pyc extension (see PEP 488). See also PYTHONOPTIMIZE .
Changed in version 3.5: Modify .pyc filenames according to PEP 488.
Do -O and also discard docstrings. Augment the filename for compiled ( bytecode ) files by adding .opt-2 before the .pyc extension (see PEP 488).
Changed in version 3.5: Modify .pyc filenames according to PEP 488.
Don’t prepend a potentially unsafe path to sys.path :
python -m module command line: Don’t prepend the current working directory.
python script.py command line: Don’t prepend the script’s directory. If it’s a symbolic link, resolve symbolic links.
python -c code and python (REPL) command lines: Don’t prepend an empty string, which means the current working directory.
See also the PYTHONSAFEPATH environment variable, and -E and -I (isolated) options.
New in version 3.11.
Don’t display the copyright and version messages even in interactive mode.
New in version 3.2.
Turn on hash randomization. This option only has an effect if the PYTHONHASHSEED environment variable is set to 0 , since hash randomization is enabled by default.
On previous versions of Python, this option turns on hash randomization, so that the __hash__() values of str and bytes objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.
Hash randomization is intended to provide protection against a denial-of-service caused by carefully chosen inputs that exploit the worst case performance of a dict construction, O(n 2 ) complexity. See http://ocert.org/advisories/ocert-2011-003.html for details.
PYTHONHASHSEED allows you to set a fixed value for the hash seed secret.
Changed in version 3.7: The option is no longer ignored.
New in version 3.2.3.
PEP 370 – Per user site-packages directory
Disable the import of the module site and the site-dependent manipulations of sys.path that it entails. Also disable these manipulations if site is explicitly imported later (call site.main() if you want them to be triggered).
Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream.
Changed in version 3.7: The text layer of the stdout and stderr streams now is unbuffered.
Print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. When given twice ( -vv ), print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit.
Changed in version 3.10: The site module reports the site-specific paths and .pth files being processed.
Warning control. Python’s warning machinery by default prints warning messages to sys.stderr .
The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default):
The action names can be abbreviated as desired and the interpreter will resolve them to the appropriate action name. For example, -Wi is the same as -Wignore .
The full form of argument is:
Empty fields match all values; trailing empty fields may be omitted. For example -W ignore::DeprecationWarning ignores all DeprecationWarning warnings.
The action field is as explained above but only applies to warnings that match the remaining fields.
The message field must match the whole warning message; this match is case-insensitive.
The category field matches the warning category (ex: DeprecationWarning ). This must be a class name; the match test whether the actual warning category of the message is a subclass of the specified warning category.
The module field matches the (fully qualified) module name; this match is case-sensitive.
The lineno field matches the line number, where zero matches all line numbers and is thus equivalent to an omitted line number.
Multiple -W options can be given; when a warning matches more than one option, the action for the last matching option is performed. Invalid -W options are ignored (though, a warning message is printed about invalid options when the first warning is issued).
Warnings can also be controlled using the PYTHONWARNINGS environment variable and from within a Python program using the warnings module. For example, the warnings.filterwarnings() function can be used to use a regular expression on the warning message.
Skip the first line of the source, allowing use of non-Unix forms of #!cmd . This is intended for a DOS specific hack only.
Reserved for various implementation-specific options. CPython currently defines the following possible values:
-X faulthandler to enable faulthandler . See also PYTHONFAULTHANDLER .
-X showrefcount to output the total reference count and number of used memory blocks when the program finishes or after each statement in the interactive interpreter. This only works on debug builds .
-X tracemalloc to start tracing Python memory allocations using the tracemalloc module. By default, only the most recent frame is stored in a traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a traceback limit of NFRAME frames. See tracemalloc.start() and PYTHONTRACEMALLOC for more information.
-X importtime to show how long each import takes. It shows module name, cumulative time (including nested imports) and self time (excluding nested imports). Note that its output may be broken in multi-threaded application. Typical usage is python3 -X importtime -c ‘import asyncio’ . See also PYTHONPROFILEIMPORTTIME .
-X dev : enable Python Development Mode , introducing additional runtime checks that are too expensive to be enabled by default.
-X utf8 enables the Python UTF-8 Mode . -X utf8=0 explicitly disables Python UTF-8 Mode (even when it would otherwise activate automatically). See also PYTHONUTF8 .
-X pycache_prefix=PATH enables writing .pyc files to a parallel tree rooted at the given directory instead of to the code tree. See also PYTHONPYCACHEPREFIX .
-X warn_default_encoding issues a EncodingWarning when the locale-specific default encoding is used for opening files. See also PYTHONWARNDEFAULTENCODING .
-X no_debug_ranges disables the inclusion of the tables mapping extra location information (end line, start column offset and end column offset) to every instruction in code objects. This is useful when smaller code objects and pyc files are desired as well as suppressing the extra visual location indicators when the interpreter displays tracebacks. See also PYTHONNODEBUGRANGES .
-X frozen_modules determines whether or not frozen modules are ignored by the import machinery. A value of “on” means they get imported and “off” means they are ignored. The default is “on” if this is an installed Python (the normal case). If it’s under development (running from the source tree) then the default is “off”. Note that the “importlib_bootstrap” and “importlib_bootstrap_external” frozen modules are always used, even if this flag is set to “off”.
It also allows passing arbitrary values and retrieving them through the sys._xoptions dictionary.
Changed in version 3.2: The -X option was added.
New in version 3.3: The -X faulthandler option.
New in version 3.4: The -X showrefcount and -X tracemalloc options.
New in version 3.6: The -X showalloccount option.
New in version 3.7: The -X importtime , -X dev and -X utf8 options.
New in version 3.8: The -X pycache_prefix option. The -X dev option now logs close() exceptions in io.IOBase destructor.
Changed in version 3.9: Using -X dev option, check encoding and errors arguments on string encoding and decoding operations.
The -X showalloccount option has been removed.
New in version 3.10: The -X warn_default_encoding option.
Deprecated since version 3.9, removed in version 3.10: The -X oldparser option.
New in version 3.11: The -X no_debug_ranges option.
New in version 3.11: The -X frozen_modules option.
New in version 3.11: The -X int_max_str_digits option.
1.1.4. Options you shouldn’t use¶
Reserved for use by Jython.
1.2. Environment variables¶
These environment variables influence Python’s behavior, they are processed before the command-line switches other than -E or -I. It is customary that command-line switches override environmental variables where there is a conflict.
Change the location of the standard Python libraries. By default, the libraries are searched in prefix /lib/python version and exec_prefix /lib/python version , where prefix and exec_prefix are installation-dependent directories, both defaulting to /usr/local .
When PYTHONHOME is set to a single directory, its value replaces both prefix and exec_prefix . To specify different values for these, set PYTHONHOME to prefix : exec_prefix .
Augment the default search path for module files. The format is the same as the shell’s PATH : one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.
In addition to normal directories, individual PYTHONPATH entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.
The default search path is installation dependent, but generally begins with prefix /lib/python version (see PYTHONHOME above). It is always appended to PYTHONPATH .
An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options . The search path can be manipulated from within a Python program as the variable sys.path .
If this is set to a non-empty string, don’t prepend a potentially unsafe path to sys.path : see the -P option for details.
New in version 3.11.
If this is set to a non-empty string, it overrides the sys.platlibdir value.
New in version 3.9.
If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. You can also change the prompts sys.ps1 and sys.ps2 and the hook sys.__interactivehook__ in this file.
Raises an auditing event cpython.run_startup with the filename as the argument when called on startup.
If this is set to a non-empty string it is equivalent to specifying the -O option. If set to an integer, it is equivalent to specifying -O multiple times.
If this is set, it names a callable using dotted-path notation. The module containing the callable will be imported and then the callable will be run by the default implementation of sys.breakpointhook() which itself is called by built-in breakpoint() . If not set, or set to the empty string, it is equivalent to the value “pdb.set_trace”. Setting this to the string “0” causes the default implementation of sys.breakpointhook() to do nothing but return immediately.
New in version 3.7.
If this is set to a non-empty string it is equivalent to specifying the -d option. If set to an integer, it is equivalent to specifying -d multiple times.
If this is set to a non-empty string it is equivalent to specifying the -i option.
This variable can also be modified by Python code using os.environ to force inspect mode on program termination.
If this is set to a non-empty string it is equivalent to specifying the -u option.
If this is set to a non-empty string it is equivalent to specifying the -v option. If set to an integer, it is equivalent to specifying -v multiple times.
If this is set, Python ignores case in import statements. This only works on Windows and macOS.
If this is set to a non-empty string, Python won’t try to write .pyc files on the import of source modules. This is equivalent to specifying the -B option.
If this is set, Python will write .pyc files in a mirror directory tree at this path, instead of in __pycache__ directories within the source tree. This is equivalent to specifying the -X pycache_prefix=PATH option.
New in version 3.8.
If this variable is not set or set to random , a random value is used to seed the hashes of str and bytes objects.
If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.
Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.
The integer must be a decimal number in the range [0,4294967295]. Specifying the value 0 will disable hash randomization.
New in version 3.2.3.
If this variable is set to an integer, it is used to configure the interpreter’s global integer string conversion length limitation .
New in version 3.11.
If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax encodingname:errorhandler . Both the encodingname and the :errorhandler parts are optional and have the same meaning as in str.encode() .
For stderr, the :errorhandler part is ignored; the handler will always be ‘backslashreplace’ .
Changed in version 3.4: The encodingname part is now optional.
Changed in version 3.6: On Windows, the encoding specified by this variable is ignored for interactive console buffers unless PYTHONLEGACYWINDOWSSTDIO is also specified. Files and pipes redirected through the standard streams are not affected.
If this is set, Python won’t add the user site-packages directory to sys.path .
PEP 370 – Per user site-packages directory
Defines the user base directory , which is used to compute the path of the user site-packages directory and Distutils installation paths for python setup.py install —user .
PEP 370 – Per user site-packages directory
If this environment variable is set, sys.argv[0] will be set to its value instead of the value got through the C runtime. Only works on macOS.
This is equivalent to the -W option. If set to a comma separated string, it is equivalent to specifying -W multiple times, with filters later in the list taking precedence over those earlier in the list.
The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default):
If this environment variable is set to a non-empty string, faulthandler.enable() is called at startup: install a handler for SIGSEGV , SIGFPE , SIGABRT , SIGBUS and SIGILL signals to dump the Python traceback. This is equivalent to -X faulthandler option.
New in version 3.3.
If this environment variable is set to a non-empty string, start tracing Python memory allocations using the tracemalloc module. The value of the variable is the maximum number of frames stored in a traceback of a trace. For example, PYTHONTRACEMALLOC=1 stores only the most recent frame. See the tracemalloc.start() function for more information. This is equivalent to setting the -X tracemalloc option.
New in version 3.4.
If this environment variable is set to a non-empty string, Python will show how long each import takes. This is equivalent to setting the -X importtime option.
New in version 3.7.
If this environment variable is set to a non-empty string, enable the debug mode of the asyncio module.
New in version 3.4.
Set the Python memory allocators and/or install debug hooks.
Set the family of memory allocators used by Python:
malloc : use the malloc() function of the C library for all domains ( PYMEM_DOMAIN_RAW , PYMEM_DOMAIN_MEM , PYMEM_DOMAIN_OBJ ).
pymalloc : use the pymalloc allocator for PYMEM_DOMAIN_MEM and PYMEM_DOMAIN_OBJ domains and use the malloc() function for the PYMEM_DOMAIN_RAW domain.
debug : install debug hooks on top of the default memory allocators .
malloc_debug : same as malloc but also install debug hooks.
pymalloc_debug : same as pymalloc but also install debug hooks.
Changed in version 3.7: Added the "default" allocator.
New in version 3.6.
If set to a non-empty string, Python will print statistics of the pymalloc memory allocator every time a new pymalloc object arena is created, and on shutdown.
This variable is ignored if the PYTHONMALLOC environment variable is used to force the malloc() allocator of the C library, or if Python is configured without pymalloc support.
Changed in version 3.6: This variable can now also be used on Python compiled in release mode. It now has no effect if set to an empty string.
If set to a non-empty string, the default filesystem encoding and error handler mode will revert to their pre-3.6 values of ‘mbcs’ and ‘replace’, respectively. Otherwise, the new defaults ‘utf-8’ and ‘surrogatepass’ are used.
This may also be enabled at runtime with sys._enablelegacywindowsfsencoding() .
New in version 3.6: See PEP 529 for more details.
If set to a non-empty string, does not use the new console reader and writer. This means that Unicode characters will be encoded according to the active console code page, rather than using utf-8.
This variable is ignored if the standard streams are redirected (to files or pipes) rather than referring to console buffers.
New in version 3.6.
If set to the value 0 , causes the main Python command line application to skip coercing the legacy ASCII-based C and POSIX locales to a more capable UTF-8 based alternative.
If this variable is not set (or is set to a value other than 0 ), the LC_ALL locale override environment variable is also not set, and the current locale reported for the LC_CTYPE category is either the default C locale, or else the explicitly ASCII-based POSIX locale, then the Python CLI will attempt to configure the following locales for the LC_CTYPE category in the order listed before loading the interpreter runtime:
If setting one of these locale categories succeeds, then the LC_CTYPE environment variable will also be set accordingly in the current process environment before the Python runtime is initialized. This ensures that in addition to being seen by both the interpreter itself and other locale-aware components running in the same process (such as the GNU readline library), the updated setting is also seen in subprocesses (regardless of whether or not those processes are running a Python interpreter), as well as in operations that query the environment rather than the current C locale (such as Python’s own locale.getdefaultlocale() ).
Configuring one of these locales (either explicitly or via the above implicit locale coercion) automatically enables the surrogateescape error handler for sys.stdin and sys.stdout ( sys.stderr continues to use backslashreplace as it does in any other locale). This stream handling behavior can be overridden using PYTHONIOENCODING as usual.
For debugging purposes, setting PYTHONCOERCECLOCALE=warn will cause Python to emit warning messages on stderr if either the locale coercion activates, or else if a locale that would have triggered coercion is still active when the Python runtime is initialized.
Also note that even when locale coercion is disabled, or when it fails to find a suitable target locale, PYTHONUTF8 will still activate by default in legacy ASCII-based locales. Both features must be disabled in order to force the interpreter to use ASCII instead of UTF-8 for system interfaces.
New in version 3.7: See PEP 538 for more details.
If this environment variable is set to a non-empty string, enable Python Development Mode , introducing additional runtime checks that are too expensive to be enabled by default. This is equivalent to setting the -X dev option.
New in version 3.7.
If set to 1 , enable the Python UTF-8 Mode .
If set to 0 , disable the Python UTF-8 Mode .
Setting any other non-empty string causes an error during interpreter initialisation.
New in version 3.7.
If this environment variable is set to a non-empty string, issue a EncodingWarning when the locale-specific default encoding is used.
New in version 3.10.
If this variable is set, it disables the inclusion of the tables mapping extra location information (end line, start column offset and end column offset) to every instruction in code objects. This is useful when smaller code objects and pyc files are desired as well as suppressing the extra visual location indicators when the interpreter displays tracebacks.
New in version 3.11.
1.2.1. Debug-mode variables¶
If set, Python will print threading debug info into stdout.
Deprecated since version 3.10, will be removed in version 3.12.
If set, Python will dump objects and reference counts still alive after shutting down the interpreter.
Need Python configured with the —with-trace-refs build option.
If set, Python will dump objects and reference counts still alive after shutting down the interpreter into a file called FILENAME.