Introducción¶
The Python standard library consists of a collection of modules. There are many ways to dissect this collection. Most modules are written in Python, but some are written in C. All can be imported into your program to add functionality. Some modules provide interfaces that are highly specific to Python, like printing a stack trace; some provide interfaces that are specific to particular operating systems, such as access to specific hardware; others provide interfaces that are specific to a particular application domain, like web development. Some modules are available in all versions and ports of Python; others are only available when the underlying system supports or requires them; yet others are available only when a particular configuration option was chosen at the time when Python was compiled and installed.
If you start reading this manual from the start, and skip to the next chapter when you get bored, you will get a reasonable overview of the available modules and application areas that are supported by the Python library. Of course, you don’t have to read it like a novel — you can also browse the table of contents (in front of the manual), or look for a specific function, module or term in the index (in the back). And finally, if you enjoy learning about random subjects, you choose a random page and read a section or two. Regardless of the order in which you read the sections of this manual, it helps to first read Built-in Functions, as the remainder of this section assumes familiarity with this material.
Ver también
The built-in functions and classes (which can be used without an
import statement) are described in Python built-ins reference.
Notas sobre la disponibilidad¶
Una nota de «Disponibilidad: Unix» significa que esta función se encuentra comúnmente en los sistemas Unix. Pero no hace ninguna afirmación sobre su existencia en un sistema operativo específico.
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.
Si una nota de disponibilidad contiene tanto una versión mínima del Kernel como una versión mínima de libc, entonces ambas condiciones deben cumplirse. Por ejemplo, una característica con la nota Availability: Linux >= 3.17 with glibc >= 2.27 requiere tanto Linux 3.17 o posterior como glibc 2.27 o posterior.
Plataformas WebAssembly¶
Las plataformas WebAssembly wasm32-emscripten (Emscripten) y wasm32-wasi (WASI) proporcionan un subconjunto de APIs POSIX. Los tiempos de ejecución de WebAssembly y los navegadores están aislados y tienen acceso limitado al host y a los recursos externos. Cualquier módulo de la biblioteca estándar de Python que utilice procesos, hilos, redes, señales u otras formas de comunicación entre procesos (IPC), no está disponible o puede no funcionar como en otros sistemas tipo Unix. La E/S de archivos, el sistema de archivos y las funciones relacionadas con permisos Unix también están restringidas. Emscripten no permite el bloqueo de E/S. Otras operaciones bloqueantes como sleep() bloquean el bucle de eventos del navegador.
Las propiedades y el comportamiento de Python en plataformas WebAssembly dependen de la versión del SDK Emscripten o del SDK WASI, de los tiempos de ejecución WASM (navegador, NodeJS, wasmtime) y de los indicadores de tiempo de compilación de Python. WebAssembly, Emscripten, y WASI son estándares en evolución; algunas características como las redes pueden ser soportadas en el futuro.
Para Python en el navegador, los usuarios deberían considerar Pyodide o PyScript. PyScript está construido sobre Pyodide, que a su vez está construido sobre CPython y Emscripten. Pyodide proporciona acceso a las APIs JavaScript y DOM de los navegadores, así como capacidades de red limitadas con las APIs XMLHttpRequest y Fetch de JavaScript.
Las APIs relacionadas con procesos no están disponibles o siempre fallan con un error. Esto incluye APIs que generan nuevos procesos (
fork(),execve()), esperan procesos (waitpid()), envían señales (kill()), o interactúan con procesos. Elsubprocessse puede importar pero no funciona.El módulo
socketestá disponible, pero es limitado y se comporta de forma diferente a otras plataformas. En Emscripten, los sockets son siempre no bloqueantes y requieren código JavaScript adicional y auxiliares en el servidor para proxy TCP a través de WebSockets; ver Emscripten Networking para más información. Vista previa de instantánea WASI 1 permite sólo sockets desde un descriptor de fichero existente.Algunas funciones son stubs que no hacen nada y siempre devuelven valores codificados.
Las funciones relacionadas con descriptores de archivos, permisos de archivos, propiedad de archivos y enlaces son limitadas y no admiten algunas operaciones. Por ejemplo, WASI no permite enlaces simbólicos con nombres de archivo absolutos.
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
multiprocessingis 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
stdoutandstderrare not connected to anything, so Python installs its own streams which redirect messages to the system log. These can be seen under the tagspython.stdoutandpython.stderrrespectively.iOS apps have a limited concept of console output.
stdoutandstderrexist, and content written tostdoutandstderrwill 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 tostdoutorstderr.Mobile apps have no usable
stdinat all. While apps can display an on-screen keyboard, this is a software feature, not something that is attached tostdin.As a result, Python modules that involve console manipulation (such as
cursesandreadline) are not available on mobile platforms.