Вступ

«Бібліотека Python» містить кілька різних видів компонентів.

Він містить типи даних, які зазвичай вважаються частиною «ядра» мови, наприклад числа та списки. Для цих типів ядро мови Python визначає форму літералів і накладає деякі обмеження на їх семантику, але не повністю визначає семантику. (З іншого боку, ядро мови визначає синтаксичні властивості, такі як правопис і пріоритети операторів.)

Бібліотека також містить вбудовані функції та винятки — об’єкти, які можуть використовуватися всім кодом Python без необхідності оператора import. Деякі з них визначені основною мовою, але багато з них не є суттєвими для основної семантики та описані лише тут.

Основна частина бібліотеки, однак, складається з набору модулів. Є багато способів розібрати цю колекцію. Деякі модулі написані мовою C і вбудовані в інтерпретатор Python; інші написані на Python та імпортовані у вихідній формі. Деякі модулі надають інтерфейси, дуже специфічні для Python, як-от друк трасування стека; деякі надають інтерфейси, які є специфічними для конкретних операційних систем, наприклад доступ до певного апаратного забезпечення; інші надають інтерфейси, які є специфічними для конкретного домену програми, наприклад Всесвітньої павутини. Деякі модулі доступні в усіх версіях і портах Python; інші доступні лише тоді, коли базова система їх підтримує або вимагає; ще інші доступні лише тоді, коли певний параметр конфігурації було вибрано під час компіляції та встановлення Python.

Цей посібник організовано «зсередини назовні»: спочатку в ньому описано вбудовані функції, типи даних і винятки, а нарешті — модулі, згруповані в розділи пов’язаних модулів.

Це означає, що якщо ви почнете читати цей посібник із самого початку та перейдете до наступного розділу, коли вам стане нудно, ви отримаєте розумний огляд доступних модулів і областей застосування, які підтримуються бібліотекою Python. Звичайно, ви не повинні читати це як роман — ви також можете переглянути зміст (перед посібником) або шукати певну функцію, модуль або термін в покажчику (у спина). І, нарешті, якщо вам подобається вивчати випадкові теми, ви обираєте випадковий номер сторінки (дивіться модуль random) і читаєте розділ або два. Незалежно від порядку, в якому ви читаєте розділи цього посібника, корисно почати з розділу Вбудовані функції, оскільки решта посібника передбачає знайомство з цим матеріалом.

Нехай шоу почнеться!

Примітки щодо наявності

  • Примітка «Доступність: Unix» означає, що ця функція зазвичай зустрічається в системах Unix. Він не робить жодних заяв про його існування в конкретній операційній системі.

  • If not separately noted, all functions that claim «Availability: Unix» are supported on macOS, iOS and Android, all of which build on a Unix core.

  • If an availability note contains both a minimum Kernel version and a minimum libc version, then both conditions must hold. For example a feature with note Availability: Linux >= 3.17 with glibc >= 2.27 requires both Linux 3.17 or newer and glibc 2.27 or newer.

WebAssembly platforms

The WebAssembly platforms wasm32-emscripten (Emscripten) and wasm32-wasi (WASI) provide a subset of POSIX APIs. WebAssembly runtimes and browsers are sandboxed and have limited access to the host and external resources. Any Python standard library module that uses processes, threading, networking, signals, or other forms of inter-process communication (IPC), is either not available or may not work as on other Unix-like systems. File I/O, file system, and Unix permission-related functions are restricted, too. Emscripten does not permit blocking I/O. Other blocking operations like sleep() block the browser event loop.

The properties and behavior of Python on WebAssembly platforms depend on the Emscripten-SDK or WASI-SDK version, WASM runtimes (browser, NodeJS, wasmtime), and Python build time flags. WebAssembly, Emscripten, and WASI are evolving standards; some features like networking may be supported in the future.

For Python in the browser, users should consider Pyodide or PyScript. PyScript is built on top of Pyodide, which itself is built on top of CPython and Emscripten. Pyodide provides access to browsers“ JavaScript and DOM APIs as well as limited networking capabilities with JavaScript’s XMLHttpRequest and Fetch APIs.

  • Process-related APIs are not available or always fail with an error. That includes APIs that spawn new processes (fork(), execve()), wait for processes (waitpid()), send signals (kill()), or otherwise interact with processes. The subprocess is importable but does not work.

  • The socket module is available, but is limited and behaves differently from other platforms. On Emscripten, sockets are always non-blocking and require additional JavaScript code and helpers on the server to proxy TCP through WebSockets; see Emscripten Networking for more information. WASI snapshot preview 1 only permits sockets from an existing file descriptor.

  • Some functions are stubs that either don’t do anything and always return hardcoded values.

  • Functions related to file descriptors, file permissions, file ownership, and links are limited and don’t support some operations. For example, WASI does not permit symlinks with absolute file names.

Mobile platforms

Android and iOS are, in most respects, POSIX operating systems. File I/O, socket handling, and threading all behave as they would on any POSIX operating system. However, there are several major differences:

  • Mobile platforms can only use Python in «embedded» mode. There is no Python REPL, and no ability to use separate executables such as python or pip. To add Python code to your mobile app, you must use the Python embedding API. For more details, see Using Python on Android and Using Python on iOS.

  • Subprocesses:

    • On Android, creating subprocesses is possible but officially unsupported. In particular, Android does not support any part of the System V IPC API, so multiprocessing is not available.

    • An iOS app cannot use any form of subprocessing, multiprocessing, or inter-process communication. If an iOS app attempts to create a subprocess, the process creating the subprocess will either lock up, or crash. An iOS app has no visibility of other applications that are running, nor any ability to communicate with other running applications, outside of the iOS-specific APIs that exist for this purpose.

  • Mobile apps have limited access to modify system resources (such as the system clock). These resources will often be readable, but attempts to modify those resources will usually fail.

  • Console input and output:

    • On Android, the native stdout and stderr are not connected to anything, so Python installs its own streams which redirect messages to the system log. These can be seen under the tags python.stdout and python.stderr respectively.

    • iOS apps have a limited concept of console output. stdout and stderr exist, and content written to stdout and stderr will be visible in logs when running in Xcode, but this content won’t be recorded in the system log. If a user who has installed your app provides their app logs as a diagnostic aid, they will not include any detail written to stdout or stderr.

    • Mobile apps have no usable stdin at all. While apps can display an on-screen keyboard, this is a software feature, not something that is attached to stdin.

      As a result, Python modules that involve console manipulation (such as curses and readline) are not available on mobile platforms.