PYTHON(1)

๐Ÿ“ฆ version 3.16.0~a1, in fedora 43, fedora 44, nixpkgs unstable

๐Ÿ’… PYTHON โ€” like, the whole manual, but make it make sense

okay bestie, welcome to PYTHON(1) from the General Commands Manual section. this is the man page for python, and it is long, so we're doing this in parts. grab a snack. ๐Ÿ“


โœจ NAME โœจ

python โ€” an interpreted, interactive, object-oriented programming language ๐Ÿ’–

yes that's the whole name section. short, sweet, iconic.


โœจ SYNOPSIS โœจ

here's the whole "how do you even call this thing" situation, verbatim, no notes:

python [ -B ] [ -b ] [ -d ] [ -E ] [ -h ] [ -i ] [ -I ]
       [ -m module-name ] [ -q ] [ -R ] [ -O ] [ -OO ] [ -P ] [ -s ] [
-S ] [ -u ]
       [ -v ] [ -V ] [ -W argument ] [ -x ] [ -X option ] [ -?  ]
       [ --check-hash-based-pycs default | always | never ]
       [ --help ] [ --help-env ] [ --help-xoptions ] [ --help-all ]
       [ -c command | script | - ] [ arguments ]

(yes the line wrapping in the original is a mess, we're keeping it exactly as-is because that's the assignment, no cap. the flags get explained later, promise ๐Ÿซถ)


โœจ DESCRIPTION โœจ

so. Python is an interpreted, interactive, object-oriented programming language, and the way it combines remarkable power with very clear syntax is honestly giving main character energy. ๐Ÿ‘‘

if you're brand new and want an intro to programming in Python, go read the Python Tutorial. that's your starting point, bestie.

then there's the Python Library Reference, which documents all the built-in and standard types, constants, functions and modules. that's the "wait what does this function do again" book. ๐Ÿ“š

and finally the Python Reference Manual, which describes the syntax and semantics of the core language in (perhaps too) much detail. like, the author literally wrote "perhaps too much detail" in the original and honestly? respect for the honesty. ๐Ÿ˜ญ

those three documents may be located via the INTERNET RESOURCES below (we'll get to that section in a later part), and they may also be installed on your system already. so like, check both. ๐Ÿ’ซ

okay so here's the glow-up part: Python's basic power can be extended with your own modules written in C or C++. on most systems those modules may be dynamically loaded. slay. ๐Ÿ”ฅ

Python is also adaptable as an extension language for existing applications. if you want hints on that, see the internal documentation. iykyk.


and lastly, if you wanna look at the documentation for installed Python modules and packages, you just run the pydoc program. that's it. that's the whole tip. โœจ


(more sections incoming in the next part โ€” we're not done, don't go anywhere ๐Ÿ’–)

โœจ COMMAND LINE OPTIONS โœจ

okay bestie, this is the good part โ€” every single flag Python will accept, and what it does to your program. no skimming, we're doing all of them ๐Ÿ’…

  • -B โ€” do NOT write .pyc files when importing, thank u. peep PYTHONDONTWRITEBYTECODE if that's more your vibe.
  • -b โ€” throw warnings when you do str(bytes_instance), str(bytearray_instance), or compare bytes/bytearray against str. and if you're feeling extra, -bb upgrades those warnings to actual errors ๐Ÿ˜ค
  • -c command โ€” give it the command to run (next section has the deets). this one ends the option list, so everything after it gets passed as arguments to your command.
  • --check-hash-based-pycs mode โ€” lets you configure how Python decides whether a hash-based .pyc file is still up to date.
  • -d โ€” turn on parser debugging output. expert mode only, and it only even exists depending on how it was compiled ๐Ÿ™ˆ
  • -E โ€” ignore environment variables like PYTHONPATH and PYTHONHOME that would otherwise change how the interpreter behaves.
  • -h, -?, --help โ€” prints the usage for the interpreter executable and dips. classic.
  • --help-env โ€” prints help specifically about Python's own environment variables, then exits.
  • --help-xoptions โ€” prints help about the implementation-specific -X options, then exits.
  • --help-all โ€” prints the COMPLETE usage info, all of it, no crumbs, then exits. โœจ
  • -i โ€” when you pass a script as the first argument, or you used -c, this drops you into interactive mode after the script or command finishes running. heads up: it does NOT read the $PYTHONSTARTUP file. super handy for poking at global variables or reading a stack trace when your script throws an exception ๐Ÿ‘‘
  • -I โ€” run Python in isolated mode. this implies -E, -P and -s. in isolated mode sys.path contains neither the script's directory nor the user's site-packages directory, and all PYTHON* environment variables are ignored too. there may be even more restrictions to stop people from injecting malicious code. locked down fr fr ๐Ÿ”’
  • -m module-name โ€” searches sys.path for the named module and runs the matching .py file as a script. this ends the option list, so everything after gets passed as arguments to the module.
  • -O โ€” removes assert statements and any code that's conditional on the value of __debug__. it also augments the filename for compiled (bytecode) files by adding .opt-1 before the .pyc extension.
  • -OO โ€” does everything -O does AND discards docstrings. the compiled (bytecode) filenames get .opt-2 before the .pyc extension instead.
  • -P โ€” don't automatically prepend a potentially unsafe path to sys.path โ€” think the current directory, the script's directory, or an empty string. see also the PYTHONSAFEPATH environment variable.
  • -q โ€” don't print the version and copyright messages. (they get suppressed in non-interactive mode anyway, so it's giving redundant but cute)
  • -R โ€” turn on hash randomization. this only actually does anything if PYTHONHASHSEED is set to 0, because hash randomization is on by default already.
  • -s โ€” don't add the user site directory to sys.path.
  • -S โ€” disables importing the module site and all the site-dependent sys.path manipulation that comes with it. it also disables those manipulations if site gets explicitly imported later.
  • -u โ€” force the stdout and stderr streams to be unbuffered. note: this does NOT affect the stdin stream, so don't come for me.
  • -v โ€” print a message every time a module is initialized, showing the place (filename or built-in module) it was loaded from. give it twice and it prints a message for every file it checks while searching for a module. it also gives you info on module cleanup at exit.
  • -V, --version โ€” prints the Python version number of the executable and exits. give it twice and it prints more info about the build ๐Ÿ‘€
  • -W argument โ€” warning control, bestie. Python's warning machinery by default prints warning messages to sys.stderr.

the simplest settings apply one particular action unconditionally to all warnings a process emits โ€” even the ones that are ignored by default:

  • -Wdefault โ€” warn once per call location
  • -Werror โ€” convert to exceptions
  • -Walways โ€” warn every time
  • -Wall โ€” same as -Walways
  • -Wmodule โ€” warn once per calling module
  • -Wonce โ€” warn once per Python process
  • -Wignore โ€” never warn

action names can be abbreviated however you like and the interpreter will resolve them to the right action. for example -Wi is the same as -Wignore.

the full form of argument is:

action:message:category:module:lineno

empty fields match all values, and trailing empty fields may be omitted. for example -W ignore::DeprecationWarning ignores all DeprecationWarning warnings.

  • the action field is as explained above, but it only applies to warnings that match the remaining fields.
  • the message field must match the start of the warning message; this match is case-insensitive.
  • the category field matches the warning category (ex: "DeprecationWarning"). this must be a class name; the match tests 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.

you can give multiple -W options; 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 about invalid options gets printed when the first warning is issued).

warnings can also be controlled with the PYTHONWARNINGS environment variable, and from inside a Python program using the warnings module. for example, the warnings.filterwarnings() function can be used to put a regular expression on the warning message ๐Ÿงš

  • -X option โ€” set an implementation-specific option. here's everything available:
    • -X cpu_count=N โ€” override the return value of os.cpu_count(). -X cpu_count=default cancels the overriding. see also PYTHON_CPU_COUNT.
    • -X dev โ€” enable CPython's "development mode", which adds extra runtime checks that are too expensive to have on by default. it will NOT be more verbose than the default if your code is correct: new warnings only get emitted when an issue is detected. the effects of developer mode are:
      • add the default warning filter, as -W default.
      • install debug hooks on memory allocators: see the PyMem_SetupDebugHooks() C function.
      • enable the faulthandler module to dump the Python traceback on a crash.
      • enable asyncio debug mode.
      • set the dev_mode attribute of sys.flags to True.
      • io.IOBase destructor logs close() exceptions.
    • -X importtime โ€” show how long every import takes. it shows the module name, cumulative time (including nested imports) and self time (excluding nested imports). heads up: its output may be broken in multi-threaded applications. typical usage is python3 -X importtime -c 'import asyncio'.

-X importtime=2 enables additional output that indicates when an imported module has already been loaded. in those cases, the string cached gets printed in both time columns.

  • -X faulthandler โ€” enable faulthandler.
  • -X frozen_modules=[on|off] โ€” whether or not frozen modules should be used. the default is "on" (or "off" if you're running a local build).
  • -X gil=[0|1] โ€” enable (1) or disable (0) the GIL. see also PYTHON_GIL. only available in builds configured with --disable-gil.
  • -X int_max_str_digits=number โ€” limit the size of intโ†”str conversions. this helps avoid denial of service attacks when parsing untrusted data. the default is sys.int_info.default_max_str_digits. 0 disables it.
  • -X no_debug_ranges โ€” disable 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 you want smaller code objects and .pyc files, and it also suppresses the extra visual location indicators when the interpreter displays tracebacks.
  • -X perf โ€” support the Linux "perf" profiler. see also PYTHONPERFSUPPORT=1.
  • -X perf_jit โ€” support the Linux "perf" profiler with DWARF support. see also PYTHON_PERF_JIT_SUPPORT=1.
  • -X presite=MOD โ€” import this module before site. see also PYTHON_PRESITE. this only works on debug builds.
  • -X pycache_prefix=PATH โ€” enable writing .pyc files to a parallel tree rooted at the given directory instead of into the code tree.
  • -X showrefcount โ€” output the total reference count and the 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 โ€” 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.
  • -X utf8 โ€” enable UTF-8 mode for operating system interfaces, overriding the default locale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it would otherwise activate automatically). see PYTHONUTF8 for more details.
  • -X warn_default_encoding โ€” enable opt-in EncodingWarning for 'encoding=None'.
  • -x โ€” skip the first line of the source. this is intended for a DOS-specific hack only.
โš ๏ธ warning bestie: the line numbers in error messages will be off by one! ๐Ÿ˜ญ

๐Ÿ’ป INTERPRETER INTERFACE ๐Ÿ’ป

okay so the interpreter interface is giving very UNIX shell energy, and here's the whole vibe:

  • when you call it with standard input hooked up to a tty device, it prompts you for commands and executes them until it reads an EOF ๐Ÿซถ
  • when you call it with a file name argument, or with a file as standard input, it reads and executes a script from that file ๐Ÿ“œ
  • when you call it with -c command, it executes the Python statement(s) you gave as command

and bestie, command can absolutely contain multiple statements separated by newlines. Leading whitespace is significant in Python statements! (not me getting caught by indentation again ๐Ÿ˜ญ). Also important: in non-interactive mode, the entire input is parsed before it is executed.

If available, the script name and additional arguments after it get passed to the script in the Python variable sys.argv, which is a list of strings โ€” and yes you must first import sys to be able to access it, no skipping that step โœจ. If no script name is given, sys.argv[0] is an empty string; if -c is used, sys.argv[0] contains the string '-c'. Note that options interpreted by the Python interpreter itself are not placed in sys.argv ๐Ÿ’….

In interactive mode, the primary prompt is >>>; the second prompt (which appears when a command is not complete) is .... The prompts can be changed by assignment to sys.ps1 or sys.ps2. The interpreter quits when it reads an EOF at a prompt. When an unhandled exception occurs, a stack trace is printed and control returns to the primary prompt; in non-interactive mode, the interpreter exits after printing the stack trace ๐Ÿ˜ญ. The interrupt signal raises the KeyboardInterrupt exception; other UNIX signals are not caught (except that SIGPIPE is sometimes ignored, in favor of the IOError exception). Error messages are written to stderr.


๐Ÿ“ FILES AND DIRECTORIES ๐Ÿ“

these are subject to difference depending on local installation conventions, so don't come for me ๐Ÿ™ˆ. ${prefix} and ${exec_prefix} are installation-dependent and should be interpreted as for GNU software; they may be the same. The default for both is /usr/local.

  • ${exec_prefix}/bin/python โ€” the recommended location of the interpreter ๐Ÿ‘‘
  • ${prefix}/lib/python<version> and ${exec_prefix}/lib/python<version> โ€” recommended locations of the directories containing the standard modules ๐Ÿ“ฆ
  • ${prefix}/include/python<version> and ${exec_prefix}/include/python<version> โ€” recommended locations of the directories containing the include files needed for developing Python extensions and embedding the interpreter ๐Ÿงฉ

๐ŸŒˆ ENVIRONMENT VARIABLES ๐ŸŒˆ

PYTHONASYNCIODEBUG

If this environment variable is set to a non-empty string, enable the debug mode of the asyncio module. ๐Ÿ›

PYTHON_BASIC_REPL

If this variable is set to any value, the interpreter will not attempt to load the Python-based REPL that requires curses and readline, and will instead use the traditional parser-based REPL. (retro era activated โœจ)

PYTHONBREAKPOINT

If this environment variable is set to 0, it disables the default debugger. It can be set to the callable of your debugger of choice. ๐Ÿช„

PYTHONCOERCECLOCALE

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.

PYTHON_COLORS

If this variable is set to 1, the interpreter will colorize various kinds of output. Setting it to 0 deactivates this behavior. ๐ŸŒˆ (color-coded everything, we love to see it)

PYTHON_CPU_COUNT

If this variable is set to a positive integer, it overrides the return values of os.cpu_count and os.process_cpu_count.

See also the -X cpu_count option. ๐Ÿ”ฅ

PYTHONDEBUG

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.

PYTHONEXECUTABLE

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 Mac OS X. ๐ŸŽ

PYTHONFAULTHANDLER

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 the -X faulthandler option.

PYTHON_FROZEN_MODULES

If this variable is set to on or off, it 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 for non-debug builds (the normal case) and off for debug builds.

See also the -X frozen_modules option. ๐ŸงŠ

PYTHON_GIL

If this variable is set to 1, the global interpreter lock (GIL) will be forced on. Setting it to 0 forces the GIL off. Only available in builds configured with --disable-gil.

This is equivalent to the -X gil option.

PYTHON_HISTORY

This environment variable can be used to set the location of a history file (on Unix, it is ~/.python_history by default). ๐Ÿ“

PYTHONNODEBUGRANGES

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.

PYTHONDONTWRITEBYTECODE

If this is set to a non-empty string it is equivalent to specifying the -B option (don't try to write .pyc files).

PYTHONDEVMODE

If this environment variable is set to a non-empty string, enable Python's "development mode", introducing additional runtime checks that are too expensive to be enabled by default.

This is equivalent to the -X dev option. ๐Ÿ› ๏ธ

PYTHONHASHSEED

If this variable is 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.

PYTHONHOME

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}. ๐Ÿ 

PYTHONINSPECT

If this is set to a non-empty string it is equivalent to specifying the -i option.

PYTHONINTMAXSTRDIGITS

Limit the maximum digit characters in an int value when converting from a string and when converting an int back to a str. A value of 0 disables the limit. Conversions to or from bases 2, 4, 8, 16, and 32 are never limited.

This is equivalent to the -X int_max_str_digits=NUMBER option. ๐Ÿ”ข

PYTHONIOENCODING

If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax encodingname:errorhandler. The errorhandler part is optional and has the same meaning as in str.encode. For stderr, the errorhandler part is ignored; the handler will always be backslashreplace. ๐Ÿฉน

PYTHONMALLOC

Set the Python memory allocators and/or install debug hooks. The available memory allocators are malloc and pymalloc. The available debug hooks are debug, malloc_debug, and pymalloc_debug.

When Python is compiled in debug mode, the default is pymalloc_debug and the debug hooks are automatically used. Otherwise, the default is pymalloc.

PYTHONMALLOCSTATS

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(3) allocator of the C library, or if Python is configured without pymalloc support.

PYTHONNOUSERSITE

If this is set to a non-empty string it is equivalent to specifying the -s option (Don't add the user site directory to sys.path).

PYTHONOPTIMIZE

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. โšก

PYTHONPATH

Augments the default search path for module files. The format is the same as the shell's $PATH: one or more directory pathnames separated by colons. Non-existent directories are silently ignored. The default search path is installation dependent, but generally begins with ${prefix}/lib/python<version> (see PYTHONHOME above). The default search path is always appended to $PYTHONPATH. If a script argument is given, the directory containing the script is inserted in the path in front of $PYTHONPATH. The search path can be manipulated from within a Python program as the variable sys.path. ๐Ÿ›ฃ๏ธ

PYTHON_PERF_JIT_SUPPORT

If this variable is set to a nonzero value, it enables support for the Linux perf profiler so Python calls can be detected by it using DWARF information. Setting to 0 disables.

See also the -X perf_jit option. ๐Ÿ“ˆ

PYTHONPERFSUPPORT

If this variable is set to a nonzero value, it enables support for the Linux perf profiler so Python calls can be detected by it. Setting to 0 disables.

See also the -X perf option.

PYTHONPLATLIBDIR

Override sys.platlibdir.

PYTHONPROFILEIMPORTTIME

If this environment variable is set to 1, Python will show how long each import takes. If set to 2, Python will include output for imported modules that have already been loaded. This is exactly equivalent to setting -X importtime on the command line. โฑ๏ธ

  • PYTHONPYCACHEPREFIX โ€” set this and Python stops sprinkling .pyc files into __pycache__ folders all over your source tree ๐ŸŒณ and instead writes them into a mirror directory tree at the path you gave. Same energy as passing -X pycache_prefix=PATH, bestie. One prefix to rule them all.
  • PYTHONSAFEPATH โ€” if it's set to a non-empty string, Python will not auto-prepend a potentially unsafe path to sys.path โ€” think the current directory, the script's own directory, or an empty string ๐Ÿ˜ณ. Your sys.path stays unbothered. Peep the -P option too, they're giving the same vibe.
  • PYTHONSTARTUP โ€” if this is the name of a readable file, the Python commands inside it get executed before the very first prompt even shows up in interactive mode โœจ. The file runs in the same name space where interactive commands run, so anything you define or import in it is just... there, no qualification needed, no extra typing. And yes, you can also change the prompts sys.ps1 and sys.ps2 from inside it. Iconic behavior tbh.
  • PYTHONTRACEMALLOC โ€” set it to a non-empty string and Python starts tracing memory allocations with the tracemalloc module ๐Ÿ”. The value of the variable is the maximum number of frames stored in a traceback of a trace. So like, PYTHONTRACEMALLOC=1 keeps only the most recent frame. Low number = short receipts, high number = the whole group chat history ๐Ÿ’€.
  • PYTHONUNBUFFERED โ€” non-empty string? That's literally just the -u option. Same thing, different font ๐Ÿ’….
  • PYTHONUSERBASE โ€” this defines the user base directory, which is what gets used to compute the path of the user site-packages directory and the installation paths for python -m pip install --user.
  • PYTHONUTF8 โ€” set it to 1 and you're enabling the Python "UTF-8 Mode" ๐ŸŒˆ. Set it to 0 and it's off. That's the whole tea.
  • PYTHONVERBOSE โ€” non-empty string means it's equivalent to -v. And if you set it to an integer, that's equivalent to passing -v multiple times ๐Ÿ‘€. So crank it up if you want the full narration.
  • PYTHONWARNDEFAULTENCODING โ€” set this to a non-empty string and Python will throw an EncodingWarning whenever the locale-specific default encoding gets used ๐Ÿšจ. A little heads-up, as a treat.
  • PYTHONWARNINGS โ€” if it's a comma-separated string, it's equivalent to passing the -W option once for each separate value. Comma-separated besties, don't forget.

๐Ÿ› Debug-mode variables

Okay so setting these only does anything in a debug build of Python โ€” meaning Python was configured with the --with-pydebug build option. Regular build? They just sit there, pretty and useless ๐ŸŽ€.

  • PYTHONDUMPREFS โ€” set it and Python dumps objects and reference counts that are still alive after shutting down the interpreter. Snitching on the survivors, fr fr.
  • PYTHONDUMPREFSFILE โ€” set it and Python dumps those same objects and reference counts still alive after shutting down the interpreter, but this time into a file ๐Ÿ“ under the path you gave as the value of this environment variable.
  • PYTHON_PRESITE โ€” if you set this to a module, that module gets imported early in the interpreter lifecycle โ€” before the site module is executed, and before the __main__ module is created ๐Ÿ•ฐ๏ธ. Only works on debug builds though, no exceptions. It's equivalent to the -X presite=module option.

๐Ÿ‘‘ AUTHOR

The Python Software Foundation: https://www.python.org/psf/


๐ŸŒˆ INTERNET RESOURCES


๐Ÿ“œ LICENSING

Python is distributed under an Open Source license ๐ŸŒฑ. Go read the file "LICENSE" in the Python source distribution for all the info on terms & conditions for accessing and otherwise using Python โ€” and for a DISCLAIMER OF ALL WARRANTIES, which is the legal way of saying "no promises bestie" ๐Ÿ˜ญ.


And that's the whole page, we ate that ๐Ÿฝ๏ธ๐Ÿ’… The footer down there is just PYTHON(1) signing off โ€” the manual section, the name, the whole shebang. Thanks for reading this far, you're literally the main character of reading documentation ๐Ÿ“–๐Ÿ‘‘ no cap.

๐Ÿ“ฆ where this page comes from