sys — System-specific parameters and functions¶
This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.
On POSIX systems where Python was built with the standard configure script, this contains the ABI flags as specified by PEP 3149.
Changed in version 3.8: Default flags became an empty string ( m flag for pymalloc has been removed).
New in version 3.2.
Append the callable hook to the list of active auditing hooks for the current (sub)interpreter.
When an auditing event is raised through the sys.audit() function, each hook will be called in the order it was added with the event name and the tuple of arguments. Native hooks added by PySys_AddAuditHook() are called first, followed by hooks added in the current (sub)interpreter. Hooks can then log the event, raise an exception to abort the operation, or terminate the process entirely.
Note that audit hooks are primarily for collecting information about internal or otherwise unobservable actions, whether by Python or libraries written in Python. They are not suitable for implementing a “sandbox”. In particular, malicious code can trivially disable or bypass hooks added using this function. At a minimum, any security-sensitive hooks must be added using the C API PySys_AddAuditHook() before initialising the runtime, and any modules allowing arbitrary memory modification (such as ctypes ) should be completely removed or closely monitored.
Calling sys.addaudithook() will itself raise an auditing event named sys.addaudithook with no arguments. If any existing hooks raise an exception derived from RuntimeError , the new hook will not be added and the exception suppressed. As a result, callers cannot assume that their hook has been added unless they control all existing hooks.
See the audit events table for all events raised by CPython, and PEP 578 for the original design discussion.
New in version 3.8.
Changed in version 3.8.1: Exceptions derived from Exception but not RuntimeError are no longer suppressed.
CPython implementation detail: When tracing is enabled (see settrace() ), Python hooks are only traced if the callable has a __cantrace__ member that is set to a true value. Otherwise, trace functions will skip the hook.
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string ‘-c’ . If no script name was passed to the Python interpreter, argv[0] is the empty string.
To loop over the standard input, or the list of files given on the command line, see the fileinput module.
On Unix, command line arguments are passed by bytes from OS. Python decodes them with filesystem encoding and “surrogateescape” error handler. When you need original bytes, you can get it by [os.fsencode(arg) for arg in sys.argv] .
Raise an auditing event and trigger any active auditing hooks. event is a string identifying the event, and args may contain optional arguments with more information about the event. The number and types of arguments for a given event are considered a public and stable API and should not be modified between releases.
For example, one auditing event is named os.chdir . This event has one argument called path that will contain the requested new working directory.
sys.audit() will call the existing auditing hooks, passing the event name and arguments, and will re-raise the first exception from any hook. In general, if an exception is raised, it should not be handled and the process should be terminated as quickly as possible. This allows hook implementations to decide how to respond to particular events: they can merely log the event or abort the operation by raising an exception.
Hooks are added using the sys.addaudithook() or PySys_AddAuditHook() functions.
The native equivalent of this function is PySys_Audit() . Using the native function is preferred when possible.
See the audit events table for all events raised by CPython.
New in version 3.8.
Set during Python startup, before site.py is run, to the same value as exec_prefix . If not running in a virtual environment , the values will stay the same; if site.py finds that a virtual environment is in use, the values of prefix and exec_prefix will be changed to point to the virtual environment, whereas base_prefix and base_exec_prefix will remain pointing to the base Python installation (the one which the virtual environment was created from).
New in version 3.3.
Set during Python startup, before site.py is run, to the same value as prefix . If not running in a virtual environment , the values will stay the same; if site.py finds that a virtual environment is in use, the values of prefix and exec_prefix will be changed to point to the virtual environment, whereas base_prefix and base_exec_prefix will remain pointing to the base Python installation (the one which the virtual environment was created from).
New in version 3.3.
An indicator of the native byte order. This will have the value ‘big’ on big-endian (most-significant byte first) platforms, and ‘little’ on little-endian (least-significant byte first) platforms.
A tuple of strings containing the names of all modules that are compiled into this Python interpreter. (This information is not available in any other way — modules.keys() only lists the imported modules.)
sys. call_tracing ( func , args ) ¶
Call func(*args) , while tracing is enabled. The tracing state is saved, and restored afterwards. This is intended to be called from a debugger from a checkpoint, to recursively debug some other code.
A string containing the copyright pertaining to the Python interpreter.
Clear the internal type cache. The type cache is used to speed up attribute and method lookups. Use the function only to drop unnecessary references during reference leak debugging.
This function should be used for internal and specialized purposes only.
Return a dictionary mapping each thread’s identifier to the topmost stack frame currently active in that thread at the time the function is called. Note that functions in the traceback module can build the call stack given such a frame.
This is most useful for debugging deadlock: this function does not require the deadlocked threads’ cooperation, and such threads’ call stacks are frozen for as long as they remain deadlocked. The frame returned for a non-deadlocked thread may bear no relationship to that thread’s current activity by the time calling code examines the frame.
This function should be used for internal and specialized purposes only.
Raises an auditing event sys._current_frames with no arguments.
Return a dictionary mapping each thread’s identifier to the topmost exception currently active in that thread at the time the function is called. If a thread is not currently handling an exception, it is not included in the result dictionary.
This is most useful for statistical profiling.
This function should be used for internal and specialized purposes only.
Raises an auditing event sys._current_exceptions with no arguments.
This hook function is called by built-in breakpoint() . By default, it drops you into the pdb debugger, but it can be set to any other function so that you can choose which debugger gets used.
The signature of this function is dependent on what it calls. For example, the default binding (e.g. pdb.set_trace() ) expects no arguments, but you might bind it to a function that expects additional arguments (positional and/or keyword). The built-in breakpoint() function passes its *args and **kws straight through. Whatever breakpointhooks() returns is returned from breakpoint() .
The default implementation first consults the environment variable PYTHONBREAKPOINT . If that is set to "0" then this function returns immediately; i.e. it is a no-op. If the environment variable is not set, or is set to the empty string, pdb.set_trace() is called. Otherwise this variable should name a function to run, using Python’s dotted-import nomenclature, e.g. package.subpackage.module.function . In this case, package.subpackage.module would be imported and the resulting module must have a callable named function() . This is run, passing in *args and **kws , and whatever function() returns, sys.breakpointhook() returns to the built-in breakpoint() function.
Note that if anything goes wrong while importing the callable named by PYTHONBREAKPOINT , a RuntimeWarning is reported and the breakpoint is ignored.
Also note that if sys.breakpointhook() is overridden programmatically, PYTHONBREAKPOINT is not consulted.
New in version 3.7.
Print low-level information to stderr about the state of CPython’s memory allocator.
If Python is built in debug mode ( configure —with-pydebug option ), it also performs some expensive internal consistency checks.
New in version 3.3.
CPython implementation detail: This function is specific to CPython. The exact output format is not defined here, and may change.
Integer specifying the handle of the Python DLL.
If value is not None , this function prints repr(value) to sys.stdout , and saves value in builtins._ . If repr(value) is not encodable to sys.stdout.encoding with sys.stdout.errors error handler (which is probably ‘strict’ ), encode it to sys.stdout.encoding with ‘backslashreplace’ error handler.
sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function to sys.displayhook .
Changed in version 3.2: Use ‘backslashreplace’ error handler on UnicodeEncodeError .
If this is true, Python won’t try to write .pyc files on the import of source modules. This value is initially set to True or False depending on the -B command line option and the PYTHONDONTWRITEBYTECODE environment variable, but you can set it yourself to control bytecode file generation.
A named tuple holding information about the environment on the wasm32-emscripten platform. The named tuple is provisional and may change in the future.
Emscripten version as tuple of ints (major, minor, micro), e.g. (3, 1, 8) .
Runtime string, e.g. browser user agent, ‘Node.js v14.18.2’ , or ‘UNKNOWN’ .
True if Python is compiled with Emscripten pthreads support.
True if Python is compiled with shared memory support.
New in version 3.11.
If this is set (not None ), Python will write bytecode-cache .pyc files to (and read them from) a parallel directory tree rooted at this directory, rather than from __pycache__ directories in the source code tree. Any __pycache__ directories in the source code tree will be ignored and new .pyc files written within the pycache prefix. Thus if you use compileall as a pre-build step, you must ensure you run it with the same pycache prefix (if any) that you will use at runtime.
A relative path is interpreted relative to the current working directory.
This value is initially set based on the value of the -X pycache_prefix=PATH command-line option or the PYTHONPYCACHEPREFIX environment variable (command-line takes precedence). If neither are set, it is None .
New in version 3.8.
This function prints out a given traceback and exception to sys.stderr .
When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook .
Raise an auditing event sys.excepthook with arguments hook , type , value , traceback when an uncaught exception occurs. If no hook has been set, hook may be None . If any hook raises an exception derived from RuntimeError the call to the hook will be suppressed. Otherwise, the audit hook exception will be reported as unraisable and sys.excepthook will be called.
The sys.unraisablehook() function handles unraisable exceptions and the threading.excepthook() function handles exception raised by threading.Thread.run() .
These objects contain the original values of breakpointhook , displayhook , excepthook , and unraisablehook at the start of the program. They are saved so that breakpointhook , displayhook and excepthook , unraisablehook can be restored in case they happen to get replaced with broken or alternative objects.
New in version 3.7: __breakpointhook__
New in version 3.8: __unraisablehook__
This function, when called while an exception handler is executing (such as an except or except* clause), returns the exception instance that was caught by this handler. When exception handlers are nested within one another, only the exception handled by the innermost handler is accessible.
If no exception handler is executing, this function returns None .
New in version 3.11.
This function returns the old-style representation of the handled exception. If an exception e is currently handled (so exception() would return e ), exc_info() returns the tuple (type(e), e, e.__traceback__) . That is, a tuple containing the type of the exception (a subclass of BaseException ), the exception itself, and a traceback object which typically encapsulates the call stack at the point where the exception last occurred.
If no exception is being handled anywhere on the stack, this function return a tuple containing three None values.
Changed in version 3.11: The type and traceback fields are now derived from the value (the exception instance), so when an exception is modified while it is being handled, the changes are reflected in the results of subsequent calls to exc_info() .
A string giving the site-specific directory prefix where the platform-dependent Python files are installed; by default, this is also ‘/usr/local’ . This can be set at build time with the —exec-prefix argument to the configure script. Specifically, all configuration files (e.g. the pyconfig.h header file) are installed in the directory exec_prefix /lib/python X.Y /config , and shared library modules are installed in exec_prefix /lib/python X.Y /lib-dynload , where X.Y is the version number of Python, for example 3.2 .
If a virtual environment is in effect, this value will be changed in site.py to point to the virtual environment. The value for the Python installation will still be available, via base_exec_prefix .
A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable, sys.executable will be an empty string or None .
Raise a SystemExit exception, signaling an intention to exit the interpreter.
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0–127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.
Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. Cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
Changed in version 3.6: If an error occurs in the cleanup after the Python interpreter has caught SystemExit (such as an error flushing buffered data in the standard streams), the exit status is changed to 120.
The named tuple flags exposes the status of command line flags. The attributes are read only.
Менеджер пакетов pip: разбираемся с установкой дополнительных библиотек в Python

Ведь не все пакеты нужны в повседневной практике или отдельном проекте, да и места они занимают не мало. Для этих целей создан удаленный репозиторий модулей https://pypi.org/ , в котором на сегодня имеется более 260 тыс. проектов на все случаи практики программирования. Вам не обязательно создавать код с нуля, так как под многие задачи уже имеется соответствующий пакет.
Работа с этим хранилищем расширений осуществляется через команду pip . Имеется и другой установщик easy_install , но он применяется существенно реже. Таким образом, пакетный менеджер pip необходим для установки, обновления, удаления и управления модулями языка Python.
2. Подготовительные мероприятия
Как видно из ответа, на данном ПК используется python версии 3.8 и pip версии 20.2.3 .
В некоторых случаях (актуально для пользователей Linux или macOS ) требуется применять команду pip3 (если в результате выполнения pip определяет, что у вас установлен python версии 2 по умолчанию). Это связано с тем, что на *nix системах присутствуют сразу обе версии языка.
Также если на вашем компьютере имеется несколько версий языка Python (например, 3.6 , 3.8 , 3.9 ), то менеджер пакетов может применяться отдельно для каждой из них:
3. Установка и удаление пакетов
При разработке сложных проектов может понадобиться установка большого количества модулей. Постоянно их скачивать из репозитория PyPi трудоемко. Для этого разработан способ загрузки пакетов локально. Они могут находиться в архивах ( *.tar.gz ) или специальных файлах с расширением .whl . Это удобно и в том случае, если нет доступа в интернет у выбранной машины, и вы заранее создали пакет со всеми необходимыми библиотеками.
Для примера запакуем модуль numpy в «колесо» ( wheel ) и установим его оттуда.
Вначале мы создали специальный локальный пакет NumPy и поместили его в текущую папку (о чем свидетельствует точка). В директории создался файл numpy-1.19.2-cp38-cp38-win32.whl . На его основании даже без интернета мы легко сможем установить данную библиотеку. Команда «—no-index» говорит о том, чтобы мы не искали модуль в репозитории PyPi , а —find-links принудительно указывает место расположения пакета. Когда речь идет о сотне пакетов, это очень удобно. Правда для этого необходимо освоить еще один инструмент: набор зависимостей (о нем – следующий раздел).
Рассмотрим вопрос удаления модулей. Если требуется удалить один пакет, то делается это по аналогии с установкой:
Читайте также
4. Файлы требований для управления пакетами
Серьезные и многоуровневые приложения никогда не обходятся одной библиотекой. Даже когда вы устанавливали тот же NumPy , вы могли заметить, что помимо самого модуля скачивались дополнительные пакеты, которые мы не запрашивали. Естественно они необходимы для правильной работы NumPy . Но откуда известно, что они нужны?
Как настроить python в Linux под свой проект?
Привет, Хабр! Меня зовут Дмитрий Алексеев, я Data Scientist и являюсь участником профессионального сообщества NTA. Сегодня расскажу как использовать python и Linux «в связке», и как это поможет облегчить вам жизнь.

Операционная система Linux получила большую популярность среди админов и разработчиков благодаря ряду преимуществ таким, как бесплатное распространение, наличие открытого исходного кода, низкие требования к вычислительным ресурсам.
Python интерпретатор предустановлен в большинстве дистрибутивов Linux. Согласно рейтингу TIOBE на текущий момент самым упоминаемым в поисковых запросах языком программирования является python. Python обладает низким порогом входа, но имеет большой спектр возможностей для применения.
Использование python и Linux «в связке» может сильно облегчить вам жизнь. Я расскажу о том, как настроить python в Linux под нужды своего проекта.
Определение виртуальной среды
Виртуальная окружение (или виртуальная среда) — это изолированная среда для проекта. Это «песочница», в рамках которой запускается приложение со своими версиями библиотек, обновление и изменение которых не затронет другие приложения, использующие те же библиотеки. Тем самым использование виртуальных сред позволяет избежать конфликтов версий.
Виртуальное окружение со всеми необходимыми настройками можно «передавать» вместе с вашим приложением. Так другому разработчику будет проще работать с вашим проектом.
Также библиотеки, которые необходимы только в одном проекте, можно подгрузить в виртуальное окружение и тем самым не засорять глобальное окружение.
Проверка версии Python
Как уже говорилось ранее, python предустановлен в большинстве дистрибутивов Linux. Я использовал версию Ubuntu 20.04.
Проверить текущую версию python можно с помощью команды: python3 -V.

Обновление пакетов
Вначале рассмотрим работу с python библиотеками в Linux.
Advanced Package Tool (apt) – это пакетный менеджер, позволяющий производить различные манипуляции с пакетами: устанавливать, удалять, обновлять, искать, загружать без установки. При этом все зависимости будут разрешаться автоматически.
Пакет – это архив, в котором содержатся бинарные и конфигурационные файлы, информация о том, куда их разместить в файловой системе и список действий по установке. В Linux python библиотеки являются пакетами.
В Linux есть список репозиториев, из которых происходит установка пакетов. Список хранится в текстовом файле /etc/apt/sources.list, а также в директории /etc/apt/sources.list.d/. При выполнении команды apt update, apt обращается к списку репозиториев и из каждого репозитория в списке получает информацию о пакетах, находящихся в нем. Вся эта информация сохраняется в операционной системе.
Если выходит новая версия библиотеки, то apt не узнает об этом, пока не будет обновлена информация в репозиториях. Поэтому, если установить пакет, предварительно не выполнив обновление, то будет установлена та версия пакета, информация о которой хранится в системе в данный момент.
Для обновления пакетов необходимо выполнить следующие две команды.
Первая команда: sudo apt update.

Вторая команда: sudo apt -y upgrade.
Флаг -y в команде обозначает автоматическое подтверждение запросов на установку.

Установка пакетов venv
Для работы с виртуальным окружением в Linux нужно установить пакет venv с помощью следующей команды: sudo apt install python3-venv.

Создание виртуальной среды в Linux
Создать виртуальное окружение можно командой python3 -m venv my_venv.
My_venv – название виртуального окружения.
Приведенная выше команда создает каталог с именем «my_venv» (а также родительские каталоги, которые ещё не существуют), содержащий менеджер пакетов pip, интерпретатор, скрипты и библиотеки.
С помощью команды ls -la можно увидеть файлы в текущей директории.

Если вы хотите создать папку с окружением в конкретной директории, то вместо названия окружения нужно указать путь к папке. Например, python3 -m venv
Далее перейду в созданный каталог и посмотрю содержимое созданной папки.

Файл pyvenv.cfg содержит ключ, который будет указывать на ту версию Python, для которой запущена эта команда.
Каталог bin содержит копию/символическую ссылку двоичных файлов Python.
Каталог include включает в себя С-заголовки, компилирующие пакеты Python.
В каталог share входит python wheels. Python wheels — это формат готовых пакетов для Python, который помогает ускорить разработку программного обеспечения за счет сокращения количества операций компиляции.
Каталог lib в виртуальной среде имеет такую же структуру, как каталог lib в глобальном окружении. И содержит папку site-packages, в которую устанавливаются библиотеки.
Активация виртуальной среды
Виртуальное окружение создано. Для начала работы с окружением нужно его активировать.
Чтобы начать использовать эту виртуальную среду, вам необходимо активировать ее, запустив скрипт под названием activate:

После активации строка консоли будет иметь префикс с именем среды.
Можно проверить версию python.

А также посмотреть список установленных в окружении библиотек.

Установим библиотеку внутри виртуальной среды
Попробую установить библиотеку в окружение.

После активации все библиотеки будут устанавливаться в данное виртуальное окружение.

Чтобы проверить как установилась библиотека, можно попробовать импортировать её.

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

Файл requirements.txt содержит все библиотеки (с указанием их версий), которые установлены в данном окружении.
Установить все эти библиотеки можно выполнив одну команду в терминале: pip install -r requirements.txt.
После успешной установки библиотек другой человек сможет запустить ваш проект на своем компьютере.
Деактивация
Чтобы выйти из виртуального окружения, необходимо ввести команду deactivate.

Заключение
В публикации я рассмотрел тему виртуальных окружений в Linux. Материал позволит вам более осознанно подходить к процессу разработки и облегчит поддержку ваших проектов. Остались вопросы, буду рад ответить на них в комментариях.
Как проверить версию модулей Python?
Я только что установил модули python: construct и statlib с помощью setuptools следующим образом:
Я хочу иметь возможность (программно) проверять их версии. Есть ли эквивалент python —version , который я могу запустить из командной строки?
Моя версия python 2.7.3 .
20 ответов
Я предлагаю использовать pip вместо easy_install. С помощью pip вы можете получить список всех установленных пакетов и их версий:
В большинстве систем linux вы можете передать это grep чтобы найти строку для конкретного пакета, который вас интересует:
Для отдельного модуля вы можете попробовать атрибут __version__ , однако есть модули без него:
Наконец, поскольку команды в вашем вопросе имеют префикс sudo , похоже, вы устанавливаете их в глобальную среду Python. Настоятельно рекомендуем взглянуть на менеджеров виртуальной среды Python, например virtualenvwrapper
Вы можете попробовать
Используйте модуль pkg_resources распространяемый вместе с библиотекой setuptools . Обратите внимание, что строка, которую вы передаете методу get_distribution должна соответствовать записи PyPI.
и если вы хотите запустить его из командной строки, вы можете сделать:
Обратите внимание, что строка, которую вы передаете методу get_distribution должна быть именем пакета, зарегистрированным в PyPI, а не именем модуля, который вы пытаетесь импортировать.
К сожалению, они не всегда одинаковы (например, вы выполняете pip install memcached , но import memcache ).
Я думаю, что это может помочь, но сначала установить пакет show для запуска pip show , а затем использовать show для поиска версии!
Лучший способ сделать это:
Для деталей конкретного пакета
pip show <package_name>
Это детализирует имя_пакета, версию, автора, местоположение и т.д.
Для более подробной информации: >>> pip help
pip должен быть обновлен, чтобы сделать это.
В Windows рекомендуем команду:
В python3 с скобками вокруг печати
module.__version__ — это хорошее первое, что нужно попробовать, но это не всегда работает.
Если вы не хотите использовать оболочку и используете pip 8 или 9, вы все равно можете использовать pip.get_installed_distributions() для получения версий из Python:
обновление: решение здесь работает в пипсах 8 и 9, но в пипсе 10 функция была перемещена из pip.get_installed_distributions в pip._internal.utils.misc.get_installed_distributions чтобы явно указать, что она не для внешнего использования. Не стоит полагаться на это, если вы используете pip 10+.
Предыдущие ответы не помогли решить мою проблему, но этот код сделал:
сначала добавьте python, pip в переменные окружения. так что вы можете выполнять свои команды из командной строки. затем просто дайте команду Python. затем импортируйте пакет
затем напечатайте название версии
Это определенно будет работать
Если вышеуказанные методы не работают, стоит попробовать следующее в python:
Обратите внимание, что .version работал у меня на нескольких других, кроме торнадо.
Когда вы устанавливаете Python, вы также получаете менеджер пакетов Python, pip. Вы можете использовать pip для получения версий модулей Python. Если вы хотите получить список всех установленных модулей Python с их номерами версий, используйте следующую команду:
Вы получите вывод:
Чтобы по отдельности найти номер версии, вы можете использовать grep для этого вывода на машинах * NIX. Например:
PyMySQL == 0.7.11 В Windows вы можете использовать findstr вместо grep. Например:
Если вы хотите узнать версию модуля в скрипте Python, вы можете использовать атрибут __version__ модуля, чтобы получить его. Обратите внимание, что не все модули поставляются с атрибутом __version__ . Например,