Debian Codegraph @

Doc/using/cmdline.rst

raw
1 .. highlight:: sh
2
3 .. ATTENTION: You probably should update Misc/python.man, too, if you modify
4 this file.
5
6 .. _using-on-general:
7
8 Command line and environment
9 ============================
10
11 The CPython interpreter scans the command line and the environment for various
12 settings.
13
14 .. impl-detail::
15
16 Other implementations' command line schemes may differ. See
17 :ref:`implementations` for further resources.
18
19
20 .. _using-on-cmdline:
21
22 Command line
23 ------------
24
25 When invoking Python, you may specify any of these options::
26
27 python [-bBdEhiIOPqRsSuvVWx?] [-c command | -m module-name | script | - ] [args]
28
29 The most common use case is, of course, a simple invocation of a script::
30
31 python myscript.py
32
33
34 .. _using-on-interface-options:
35
36 Interface options
37 ~~~~~~~~~~~~~~~~~
38
39 The interpreter interface resembles that of the UNIX shell, but provides some
40 additional methods of invocation:
41
42 * When called with standard input connected to a tty device, it prompts for
43 commands and executes them until an EOF (an end-of-file character, you can
44 produce that with :kbd:`Ctrl-D` on UNIX or :kbd:`Ctrl-Z, Enter` on Windows) is read.
45 For more on interactive mode, see :ref:`tut-interac`.
46 * When called with a file name argument or with a file as standard input, it
47 reads and executes a script from that file.
48 * When called with a directory name argument, it reads and executes an
49 appropriately named script from that directory.
50 * When called with ``-c command``, it executes the Python statement(s) given as
51 *command*. Here *command* may contain multiple statements separated by
52 newlines. Leading whitespace is significant in Python statements!
53 * When called with ``-m module-name``, the given module is located using the standard
54 import mechanism and executed as a script.
55
56 In non-interactive mode, the entire input is parsed before it is executed.
57
58 An interface option terminates the list of options consumed by the interpreter,
59 all consecutive arguments will end up in :data:`sys.argv` -- note that the first
60 element, subscript zero (``sys.argv[0]``), is a string reflecting the program's
61 source.
62
63 .. option:: -c <command>
64
65 Execute the Python code in *command*. *command* can be one or more
66 statements separated by newlines, with significant leading whitespace as in
67 normal module code.
68
69 If this option is given, the first element of :data:`sys.argv` will be
70 ``"-c"`` and the current directory will be added to the start of
71 :data:`sys.path` (allowing modules in that directory to be imported as top
72 level modules).
73
74 .. audit-event:: cpython.run_command command cmdoption-c
75
76 .. option:: -m <module-name>
77
78 Locate the module using the standard import mechanism and execute its contents
79 as the :mod:`__main__` module.
80
81 Since the argument is a *module* name, you must not give a file extension
82 (``.py``). The module name should be a valid absolute Python module name, but
83 the implementation may not always enforce this (e.g. it may allow you to
84 use a name that includes a hyphen).
85
86 Package names (including namespace packages) are also permitted. When a
87 package name is supplied instead
88 of a normal module, the interpreter will execute ``<pkg>.__main__`` as
89 the main module. This behaviour is deliberately similar to the handling
90 of directories and zipfiles that are passed to the interpreter as the
91 script argument.
92
93 .. note::
94
95 This option cannot be used with built-in modules and extension modules
96 written in C, since they do not have Python module files. However, it
97 can still be used for precompiled modules, even if the original source
98 file is not available.
99
100 If this option is given, the first element of :data:`sys.argv` will be the
101 full path to the module file (while the module file is being located, the
102 first element will be set to ``"-m"``). As with the :option:`-c` option,
103 the current directory will be added to the start of :data:`sys.path`.
104
105 :option:`-I` option can be used to run the script in isolated mode where
106 :data:`sys.path` contains neither the current directory nor the user's
107 site-packages directory. All ``PYTHON*`` environment variables are
108 ignored, too.
109
110 Many standard library modules contain code that is invoked on their execution
111 as a script. An example is the :mod:`timeit` module::
112
113 python -m timeit -s "setup here" "benchmarked code here"
114 python -m timeit -h # for details
115
116 .. audit-event:: cpython.run_module module-name cmdoption-m
117
118 .. seealso::
119 :func:`runpy.run_module`
120 Equivalent functionality directly available to Python code
121
122 :pep:`338` -- Executing modules as scripts
123
124 .. versionchanged:: 3.1
125 Supply the package name to run a ``__main__`` submodule.
126
127 .. versionchanged:: 3.4
128 namespace packages are also supported
129
130 .. _cmdarg-dash:
131
132 .. describe:: -
133
134 Read commands from standard input (:data:`sys.stdin`). If standard input is
135 a terminal, :option:`-i` is implied.
136
137 If this option is given, the first element of :data:`sys.argv` will be
138 ``"-"`` and the current directory will be added to the start of
139 :data:`sys.path`.
140
141 .. audit-event:: cpython.run_stdin "" ""
142
143 .. _cmdarg-script:
144
145 .. describe:: <script>
146
147 Execute the Python code contained in *script*, which must be a filesystem
148 path (absolute or relative) referring to either a Python file, a directory
149 containing a ``__main__.py`` file, or a zipfile containing a
150 ``__main__.py`` file.
151
152 If this option is given, the first element of :data:`sys.argv` will be the
153 script name as given on the command line.
154
155 If the script name refers directly to a Python file, the directory
156 containing that file is added to the start of :data:`sys.path`, and the
157 file is executed as the :mod:`__main__` module.
158
159 If the script name refers to a directory or zipfile, the script name is
160 added to the start of :data:`sys.path` and the ``__main__.py`` file in
161 that location is executed as the :mod:`__main__` module.
162
163 :option:`-I` option can be used to run the script in isolated mode where
164 :data:`sys.path` contains neither the script's directory nor the user's
165 site-packages directory. All ``PYTHON*`` environment variables are
166 ignored, too.
167
168 .. audit-event:: cpython.run_file filename
169
170 .. seealso::
171 :func:`runpy.run_path`
172 Equivalent functionality directly available to Python code
173
174
175 If no interface option is given, :option:`-i` is implied, ``sys.argv[0]`` is
176 an empty string (``""``) and the current directory will be added to the
177 start of :data:`sys.path`. Also, tab-completion and history editing is
178 automatically enabled, if available on your platform (see
179 :ref:`rlcompleter-config`).
180
181 .. seealso:: :ref:`tut-invoking`
182
183 .. versionchanged:: 3.4
184 Automatic enabling of tab-completion and history editing.
185
186
187 .. _using-on-generic-options:
188
189 Generic options
190 ~~~~~~~~~~~~~~~
191
192 .. option:: -?
193 -h
194 --help
195
196 Print a short description of all command line options and corresponding
197 environment variables and exit.
198
199 .. option:: --help-env
200
201 Print a short description of Python-specific environment variables
202 and exit.
203
204 .. versionadded:: 3.11
205
206 .. option:: --help-xoptions
207
208 Print a description of implementation-specific :option:`-X` options
209 and exit.
210
211 .. versionadded:: 3.11
212
213 .. option:: --help-all
214
215 Print complete usage information and exit.
216
217 .. versionadded:: 3.11
218
219 .. option:: -V
220 --version
221
222 Print the Python version number and exit. Example output could be:
223
224 .. code-block:: none
225
226 Python 3.8.0b2+
227
228 When given twice, print more information about the build, like:
229
230 .. code-block:: none
231
232 Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00)
233 [GCC 6.2.0 20161005]
234
235 .. versionadded:: 3.6
236 The ``-VV`` option.
237
238
239 .. _using-on-misc-options:
240
241 Miscellaneous options
242 ~~~~~~~~~~~~~~~~~~~~~
243
244 .. option:: -b
245
246 Issue a warning when converting :class:`bytes` or :class:`bytearray` to
247 :class:`str` without specifying encoding or comparing :class:`!bytes` or
248 :class:`!bytearray` with :class:`!str` or :class:`!bytes` with :class:`int`.
249 Issue an error when the option is given twice (:option:`!-bb`).
250
251 .. versionchanged:: 3.5
252 Affects also comparisons of :class:`bytes` with :class:`int`.
253
254 .. option:: -B
255
256 If given, Python won't try to write ``.pyc`` files on the
257 import of source modules. See also :envvar:`PYTHONDONTWRITEBYTECODE`.
258
259
260 .. option:: --check-hash-based-pycs default|always|never
261
262 Control the validation behavior of hash-based ``.pyc`` files. See
263 :ref:`pyc-invalidation`. When set to ``default``, checked and unchecked
264 hash-based bytecode cache files are validated according to their default
265 semantics. When set to ``always``, all hash-based ``.pyc`` files, whether
266 checked or unchecked, are validated against their corresponding source
267 file. When set to ``never``, hash-based ``.pyc`` files are not validated
268 against their corresponding source files.
269
270 The semantics of timestamp-based ``.pyc`` files are unaffected by this
271 option.
272
273
274 .. option:: -d
275
276 Turn on parser debugging output (for expert only).
277 See also the :envvar:`PYTHONDEBUG` environment variable.
278
279 This option requires a :ref:`debug build of Python <debug-build>`, otherwise
280 it's ignored.
281
282
283 .. option:: -E
284
285 Ignore all ``PYTHON*`` environment variables, e.g.
286 :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
287
288 See also the :option:`-P` and :option:`-I` (isolated) options.
289
290
291 .. option:: -i
292
293 Enter interactive mode after execution.
294
295 Using the :option:`-i` option will enter interactive mode in any of the following circumstances\:
296
297 * When a script is passed as first argument
298 * When the :option:`-c` option is used
299 * When the :option:`-m` option is used
300
301 Interactive mode will start even when :data:`sys.stdin` does not appear to be a terminal. The
302 :envvar:`PYTHONSTARTUP` file is not read.
303
304 This can be useful to inspect global variables or a stack trace when a script
305 raises an exception. See also :envvar:`PYTHONINSPECT`.
306
307
308 .. option:: -I
309
310 Run Python in isolated mode. This also implies :option:`-E`, :option:`-P`
311 and :option:`-s` options.
312
313 In isolated mode :data:`sys.path` contains neither the script's directory nor
314 the user's site-packages directory. All ``PYTHON*`` environment
315 variables are ignored, too. Further restrictions may be imposed to prevent
316 the user from injecting malicious code.
317
318 .. versionadded:: 3.4
319
320
321 .. option:: -O
322
323 Remove assert statements and any code conditional on the value of
324 :const:`__debug__`. Augment the filename for compiled
325 (:term:`bytecode`) files by adding ``.opt-1`` before the ``.pyc``
326 extension (see :pep:`488`). See also :envvar:`PYTHONOPTIMIZE`.
327
328 .. versionchanged:: 3.5
329 Modify ``.pyc`` filenames according to :pep:`488`.
330
331
332 .. option:: -OO
333
334 Do :option:`-O` and also discard docstrings. Augment the filename
335 for compiled (:term:`bytecode`) files by adding ``.opt-2`` before the
336 ``.pyc`` extension (see :pep:`488`).
337
338 .. versionchanged:: 3.5
339 Modify ``.pyc`` filenames according to :pep:`488`.
340
341
342 .. option:: -P
343
344 Don't prepend a potentially unsafe path to :data:`sys.path`:
345
346 * ``python -m module`` command line: Don't prepend the current working
347 directory.
348 * ``python script.py`` command line: Don't prepend the script's directory.
349 If it's a symbolic link, resolve symbolic links.
350 * ``python -c code`` and ``python`` (REPL) command lines: Don't prepend an
351 empty string, which means the current working directory.
352
353 See also the :envvar:`PYTHONSAFEPATH` environment variable, and :option:`-E`
354 and :option:`-I` (isolated) options.
355
356 .. versionadded:: 3.11
357
358
359 .. option:: -q
360
361 Don't display the copyright and version messages even in interactive mode.
362
363 .. versionadded:: 3.2
364
365
366 .. option:: -R
367
368 Turn on hash randomization. This option only has an effect if the
369 :envvar:`PYTHONHASHSEED` environment variable is set to anything other
370 than ``random``, since hash randomization is enabled by default.
371
372 On previous versions of Python, this option turns on hash randomization,
373 so that the :meth:`~object.__hash__` values of str and bytes objects
374 are "salted" with an unpredictable random value. Although they remain
375 constant within an individual Python process, they are not predictable
376 between repeated invocations of Python.
377
378 Hash randomization is intended to provide protection against a
379 denial-of-service caused by carefully chosen inputs that exploit the worst
380 case performance of a dict construction, *O*\ (*n*\ :sup:`2`) complexity. See
381 https://ocert.org/advisories/ocert-2011-003.html for details.
382
383 :envvar:`PYTHONHASHSEED` allows you to set a fixed value for the hash
384 seed secret.
385
386 .. versionadded:: 3.2.3
387
388 .. versionchanged:: 3.7
389 The option is no longer ignored.
390
391
392 .. option:: -s
393
394 Don't add the :data:`user site-packages directory <site.USER_SITE>` to
395 :data:`sys.path`.
396
397 See also :envvar:`PYTHONNOUSERSITE`.
398
399 .. seealso::
400
401 :pep:`370` -- Per user site-packages directory
402
403
404 .. option:: -S
405
406 Disable the import of the module :mod:`site` and the site-dependent
407 manipulations of :data:`sys.path` that it entails. Also disable these
408 manipulations if :mod:`site` is explicitly imported later (call
409 :func:`site.main` if you want them to be triggered).
410
411
412 .. option:: -u
413
414 Force the stdout and stderr streams to be unbuffered. This option has no
415 effect on the stdin stream.
416
417 See also :envvar:`PYTHONUNBUFFERED`.
418
419 .. versionchanged:: 3.7
420 The text layer of the stdout and stderr streams now is unbuffered.
421
422
423 .. option:: -v
424
425 Print a message each time a module is initialized, showing the place
426 (filename or built-in module) from which it is loaded. When given twice
427 (:option:`!-vv`), print a message for each file that is checked for when
428 searching for a module. Also provides information on module cleanup at exit.
429
430 .. versionchanged:: 3.10
431 The :mod:`site` module reports the site-specific paths
432 and :file:`.pth` files being processed.
433
434 See also :envvar:`PYTHONVERBOSE`.
435
436
437 .. _using-on-warnings:
438 .. option:: -W arg
439
440 Warning control. Python's warning machinery by default prints warning
441 messages to :data:`sys.stderr`.
442
443 The simplest settings apply a particular action unconditionally to all
444 warnings emitted by a process (even those that are otherwise ignored by
445 default)::
446
447 -Wdefault # Warn once per call location
448 -Werror # Convert to exceptions
449 -Walways # Warn every time
450 -Wall # Same as -Walways
451 -Wmodule # Warn once per calling module
452 -Wonce # Warn once per Python process
453 -Wignore # Never warn
454
455 The action names can be abbreviated as desired and the interpreter will
456 resolve them to the appropriate action name. For example, ``-Wi`` is the
457 same as ``-Wignore``.
458
459 The full form of argument is::
460
461 action:message:category:module:lineno
462
463 Empty fields match all values; trailing empty fields may be omitted. For
464 example ``-W ignore::DeprecationWarning`` ignores all DeprecationWarning
465 warnings.
466
467 The *action* field is as explained above but only applies to warnings that
468 match the remaining fields.
469
470 The *message* field must match the whole warning message; this match is
471 case-insensitive.
472
473 The *category* field matches the warning category
474 (ex: ``DeprecationWarning``). This must be a class name; the match test
475 whether the actual warning category of the message is a subclass of the
476 specified warning category.
477
478 The *module* field matches the (fully qualified) module name; this match is
479 case-sensitive.
480
481 The *lineno* field matches the line number, where zero matches all line
482 numbers and is thus equivalent to an omitted line number.
483
484 Multiple :option:`-W` options can be given; when a warning matches more than
485 one option, the action for the last matching option is performed. Invalid
486 :option:`-W` options are ignored (though, a warning message is printed about
487 invalid options when the first warning is issued).
488
489 Warnings can also be controlled using the :envvar:`PYTHONWARNINGS`
490 environment variable and from within a Python program using the
491 :mod:`warnings` module. For example, the :func:`warnings.filterwarnings`
492 function can be used to use a regular expression on the warning message.
493
494 See :ref:`warning-filter` and :ref:`describing-warning-filters` for more
495 details.
496
497
498 .. option:: -x
499
500 Skip the first line of the source, allowing use of non-Unix forms of
501 ``#!cmd``. This is intended for a DOS specific hack only.
502
503
504 .. option:: -X
505
506 Reserved for various implementation-specific options. CPython currently
507 defines the following possible values:
508
509 * ``-X faulthandler`` to enable :mod:`faulthandler`.
510 See also :envvar:`PYTHONFAULTHANDLER`.
511
512 .. versionadded:: 3.3
513
514 * ``-X showrefcount`` to output the total reference count and number of used
515 memory blocks when the program finishes or after each statement in the
516 interactive interpreter. This only works on :ref:`debug builds
517 <debug-build>`.
518
519 .. versionadded:: 3.4
520
521 * ``-X tracemalloc`` to start tracing Python memory allocations using the
522 :mod:`tracemalloc` module. By default, only the most recent frame is
523 stored in a traceback of a trace. Use ``-X tracemalloc=NFRAME`` to start
524 tracing with a traceback limit of *NFRAME* frames.
525 See :func:`tracemalloc.start` and :envvar:`PYTHONTRACEMALLOC`
526 for more information.
527
528 .. versionadded:: 3.4
529
530 * ``-X int_max_str_digits`` configures the :ref:`integer string conversion
531 length limitation <int_max_str_digits>`. See also
532 :envvar:`PYTHONINTMAXSTRDIGITS`.
533
534 .. versionadded:: 3.11
535
536 * ``-X importtime`` to show how long each import takes. It shows module
537 name, cumulative time (including nested imports) and self time (excluding
538 nested imports). Note that its output may be broken in multi-threaded
539 application. Typical usage is ``python3 -X importtime -c 'import
540 asyncio'``. See also :envvar:`PYTHONPROFILEIMPORTTIME`.
541
542 .. versionadded:: 3.7
543
544 * ``-X dev``: enable :ref:`Python Development Mode <devmode>`, introducing
545 additional runtime checks that are too expensive to be enabled by
546 default. See also :envvar:`PYTHONDEVMODE`.
547
548 .. versionadded:: 3.7
549
550 * ``-X utf8`` enables the :ref:`Python UTF-8 Mode <utf8-mode>`.
551 ``-X utf8=0`` explicitly disables :ref:`Python UTF-8 Mode <utf8-mode>`
552 (even when it would otherwise activate automatically).
553 See also :envvar:`PYTHONUTF8`.
554
555 .. versionadded:: 3.7
556
557 * ``-X pycache_prefix=PATH`` enables writing ``.pyc`` files to a parallel
558 tree rooted at the given directory instead of to the code tree. See also
559 :envvar:`PYTHONPYCACHEPREFIX`.
560
561 .. versionadded:: 3.8
562
563 * ``-X warn_default_encoding`` issues a :class:`EncodingWarning` when the
564 locale-specific default encoding is used for opening files.
565 See also :envvar:`PYTHONWARNDEFAULTENCODING`.
566
567 .. versionadded:: 3.10
568
569 * ``-X no_debug_ranges`` disables the inclusion of the tables mapping extra
570 location information (end line, start column offset and end column offset)
571 to every instruction in code objects. This is useful when smaller code
572 objects and pyc files are desired as well as suppressing the extra visual
573 location indicators when the interpreter displays tracebacks. See also
574 :envvar:`PYTHONNODEBUGRANGES`.
575
576 .. versionadded:: 3.11
577
578 * ``-X frozen_modules`` determines whether or not frozen modules are
579 ignored by the import machinery. A value of ``on`` means they get
580 imported and ``off`` means they are ignored. The default is ``on``
581 if this is an installed Python (the normal case). If it's under
582 development (running from the source tree) then the default is ``off``.
583 Note that the :mod:`!importlib_bootstrap` and
584 :mod:`!importlib_bootstrap_external` frozen modules are always used, even
585 if this flag is set to ``off``. See also :envvar:`PYTHON_FROZEN_MODULES`.
586
587 .. versionadded:: 3.11
588
589 * ``-X perf`` enables support for the Linux ``perf`` profiler.
590 When this option is provided, the ``perf`` profiler will be able to
591 report Python calls. This option is only available on some platforms and
592 will do nothing if is not supported on the current system. The default value
593 is "off". See also :envvar:`PYTHONPERFSUPPORT` and :ref:`perf_profiling`.
594
595 .. versionadded:: 3.12
596
597 * ``-X perf_jit`` enables support for the Linux ``perf`` profiler with DWARF
598 support. When this option is provided, the ``perf`` profiler will be able
599 to report Python calls using DWARF information. This option is only available on
600 some platforms and will do nothing if is not supported on the current
601 system. The default value is "off". See also :envvar:`PYTHON_PERF_JIT_SUPPORT`
602 and :ref:`perf_profiling`.
603
604 .. versionadded:: 3.13
605
606 * :samp:`-X cpu_count={n}` overrides :func:`os.cpu_count`,
607 :func:`os.process_cpu_count`, and :func:`multiprocessing.cpu_count`.
608 *n* must be greater than or equal to 1.
609 This option may be useful for users who need to limit CPU resources of a
610 container system. See also :envvar:`PYTHON_CPU_COUNT`.
611 If *n* is ``default``, nothing is overridden.
612
613 .. versionadded:: 3.13
614
615 * :samp:`-X presite={package.module}` specifies a module that should be
616 imported before the :mod:`site` module is executed and before the
617 :mod:`__main__` module exists. Therefore, the imported module isn't
618 :mod:`__main__`. This can be used to execute code early during Python
619 initialization. Python needs to be :ref:`built in debug mode <debug-build>`
620 for this option to exist. See also :envvar:`PYTHON_PRESITE`.
621
622 .. versionadded:: 3.13
623
624 * :samp:`-X gil={0,1}` forces the GIL to be disabled or enabled,
625 respectively. Setting to ``0`` is only available in builds configured with
626 :option:`--disable-gil`. See also :envvar:`PYTHON_GIL` and
627 :ref:`whatsnew313-free-threaded-cpython`.
628
629 .. versionadded:: 3.13
630
631 It also allows passing arbitrary values and retrieving them through the
632 :data:`sys._xoptions` dictionary.
633
634 .. versionadded:: 3.2
635
636 .. versionchanged:: 3.9
637 Removed the ``-X showalloccount`` option.
638
639 .. versionchanged:: 3.10
640 Removed the ``-X oldparser`` option.
641
642 .. _using-on-controlling-color:
643
644 Controlling color
645 ~~~~~~~~~~~~~~~~~
646
647 The Python interpreter is configured by default to use colors to highlight
648 output in certain situations such as when displaying tracebacks. This
649 behavior can be controlled by setting different environment variables.
650
651 Setting the environment variable ``TERM`` to ``dumb`` will disable color.
652
653 If the |FORCE_COLOR|_ environment variable is set, then color will be
654 enabled regardless of the value of TERM. This is useful on CI systems which
655 aren’t terminals but can still display ANSI escape sequences.
656
657 If the |NO_COLOR|_ environment variable is set, Python will disable all color
658 in the output. This takes precedence over ``FORCE_COLOR``.
659
660 All these environment variables are used also by other tools to control color
661 output. To control the color output only in the Python interpreter, the
662 :envvar:`PYTHON_COLORS` environment variable can be used. This variable takes
663 precedence over ``NO_COLOR``, which in turn takes precedence over
664 ``FORCE_COLOR``.
665
666 .. Apparently this how you hack together a formatted link:
667
668 .. |FORCE_COLOR| replace:: ``FORCE_COLOR``
669 .. _FORCE_COLOR: https://force-color.org/
670
671 .. |NO_COLOR| replace:: ``NO_COLOR``
672 .. _NO_COLOR: https://no-color.org/
673
674 Options you shouldn't use
675 ~~~~~~~~~~~~~~~~~~~~~~~~~
676
677 .. option:: -J
678
679 Reserved for use by Jython_.
680
681 .. _Jython: https://www.jython.org/
682
683
684 .. _using-on-envvars:
685
686 Environment variables
687 ---------------------
688
689 These environment variables influence Python's behavior, they are processed
690 before the command-line switches other than -E or -I. It is customary that
691 command-line switches override environmental variables where there is a
692 conflict.
693
694 .. envvar:: PYTHONHOME
695
696 Change the location of the standard Python libraries. By default, the
697 libraries are searched in :file:`{prefix}/lib/python{version}` and
698 :file:`{exec_prefix}/lib/python{version}`, where :file:`{prefix}` and
699 :file:`{exec_prefix}` are installation-dependent directories, both defaulting
700 to :file:`/usr/local`.
701
702 When :envvar:`PYTHONHOME` is set to a single directory, its value replaces
703 both :file:`{prefix}` and :file:`{exec_prefix}`. To specify different values
704 for these, set :envvar:`PYTHONHOME` to :file:`{prefix}:{exec_prefix}`.
705
706
707 .. envvar:: PYTHONPATH
708
709 Augment the default search path for module files. The format is the same as
710 the shell's :envvar:`PATH`: one or more directory pathnames separated by
711 :data:`os.pathsep` (e.g. colons on Unix or semicolons on Windows).
712 Non-existent directories are silently ignored.
713
714 In addition to normal directories, individual :envvar:`PYTHONPATH` entries
715 may refer to zipfiles containing pure Python modules (in either source or
716 compiled form). Extension modules cannot be imported from zipfiles.
717
718 The default search path is installation dependent, but generally begins with
719 :file:`{prefix}/lib/python{version}` (see :envvar:`PYTHONHOME` above). It
720 is *always* appended to :envvar:`PYTHONPATH`.
721
722 An additional directory will be inserted in the search path in front of
723 :envvar:`PYTHONPATH` as described above under
724 :ref:`using-on-interface-options`. The search path can be manipulated from
725 within a Python program as the variable :data:`sys.path`.
726
727
728 .. envvar:: PYTHONSAFEPATH
729
730 If this is set to a non-empty string, don't prepend a potentially unsafe
731 path to :data:`sys.path`: see the :option:`-P` option for details.
732
733 .. versionadded:: 3.11
734
735
736 .. envvar:: PYTHONPLATLIBDIR
737
738 If this is set to a non-empty string, it overrides the :data:`sys.platlibdir`
739 value.
740
741 .. versionadded:: 3.9
742
743
744 .. envvar:: PYTHONSTARTUP
745
746 If this is the name of a readable file, the Python commands in that file are
747 executed before the first prompt is displayed in interactive mode. The file
748 is executed in the same namespace where interactive commands are executed so
749 that objects defined or imported in it can be used without qualification in
750 the interactive session. You can also change the prompts :data:`sys.ps1` and
751 :data:`sys.ps2` and the hook :data:`sys.__interactivehook__` in this file.
752
753 .. audit-event:: cpython.run_startup filename envvar-PYTHONSTARTUP
754
755 Raises an :ref:`auditing event <auditing>` ``cpython.run_startup`` with
756 the filename as the argument when called on startup.
757
758
759 .. envvar:: PYTHONOPTIMIZE
760
761 If this is set to a non-empty string it is equivalent to specifying the
762 :option:`-O` option. If set to an integer, it is equivalent to specifying
763 :option:`-O` multiple times.
764
765
766 .. envvar:: PYTHONBREAKPOINT
767
768 If this is set, it names a callable using dotted-path notation. The module
769 containing the callable will be imported and then the callable will be run
770 by the default implementation of :func:`sys.breakpointhook` which itself is
771 called by built-in :func:`breakpoint`. If not set, or set to the empty
772 string, it is equivalent to the value "pdb.set_trace". Setting this to the
773 string "0" causes the default implementation of :func:`sys.breakpointhook`
774 to do nothing but return immediately.
775
776 .. versionadded:: 3.7
777
778 .. envvar:: PYTHONDEBUG
779
780 If this is set to a non-empty string it is equivalent to specifying the
781 :option:`-d` option. If set to an integer, it is equivalent to specifying
782 :option:`-d` multiple times.
783
784 This environment variable requires a :ref:`debug build of Python
785 <debug-build>`, otherwise it's ignored.
786
787
788 .. envvar:: PYTHONINSPECT
789
790 If this is set to a non-empty string it is equivalent to specifying the
791 :option:`-i` option.
792
793 This variable can also be modified by Python code using :data:`os.environ`
794 to force inspect mode on program termination.
795
796 .. audit-event:: cpython.run_stdin "" ""
797
798 .. versionchanged:: 3.12.5 (also 3.11.10, 3.10.15, 3.9.20, and 3.8.20)
799 Emits audit events.
800
801 .. versionchanged:: 3.13
802 Uses PyREPL if possible, in which case :envvar:`PYTHONSTARTUP` is
803 also executed. Emits audit events.
804
805
806 .. envvar:: PYTHONUNBUFFERED
807
808 If this is set to a non-empty string it is equivalent to specifying the
809 :option:`-u` option.
810
811
812 .. envvar:: PYTHONVERBOSE
813
814 If this is set to a non-empty string it is equivalent to specifying the
815 :option:`-v` option. If set to an integer, it is equivalent to specifying
816 :option:`-v` multiple times.
817
818
819 .. envvar:: PYTHONCASEOK
820
821 If this is set, Python ignores case in :keyword:`import` statements. This
822 only works on Windows and macOS.
823
824
825 .. envvar:: PYTHONDONTWRITEBYTECODE
826
827 If this is set to a non-empty string, Python won't try to write ``.pyc``
828 files on the import of source modules. This is equivalent to
829 specifying the :option:`-B` option.
830
831
832 .. envvar:: PYTHONPYCACHEPREFIX
833
834 If this is set, Python will write ``.pyc`` files in a mirror directory tree
835 at this path, instead of in ``__pycache__`` directories within the source
836 tree. This is equivalent to specifying the :option:`-X`
837 ``pycache_prefix=PATH`` option.
838
839 .. versionadded:: 3.8
840
841
842 .. envvar:: PYTHONHASHSEED
843
844 If this variable is not set or set to ``random``, a random value is used
845 to seed the hashes of str and bytes objects.
846
847 If :envvar:`PYTHONHASHSEED` is set to an integer value, it is used as a fixed
848 seed for generating the hash() of the types covered by the hash
849 randomization.
850
851 Its purpose is to allow repeatable hashing, such as for selftests for the
852 interpreter itself, or to allow a cluster of python processes to share hash
853 values.
854
855 The integer must be a decimal number in the range [0,4294967295]. Specifying
856 the value 0 will disable hash randomization.
857
858 .. versionadded:: 3.2.3
859
860 .. envvar:: PYTHONINTMAXSTRDIGITS
861
862 If this variable is set to an integer, it is used to configure the
863 interpreter's global :ref:`integer string conversion length limitation
864 <int_max_str_digits>`.
865
866 .. versionadded:: 3.11
867
868 .. envvar:: PYTHONIOENCODING
869
870 If this is set before running the interpreter, it overrides the encoding used
871 for stdin/stdout/stderr, in the syntax ``encodingname:errorhandler``. Both
872 the ``encodingname`` and the ``:errorhandler`` parts are optional and have
873 the same meaning as in :func:`str.encode`.
874
875 For stderr, the ``:errorhandler`` part is ignored; the handler will always be
876 ``'backslashreplace'``.
877
878 .. versionchanged:: 3.4
879 The ``encodingname`` part is now optional.
880
881 .. versionchanged:: 3.6
882 On Windows, the encoding specified by this variable is ignored for interactive
883 console buffers unless :envvar:`PYTHONLEGACYWINDOWSSTDIO` is also specified.
884 Files and pipes redirected through the standard streams are not affected.
885
886 .. envvar:: PYTHONNOUSERSITE
887
888 If this is set, Python won't add the :data:`user site-packages directory
889 <site.USER_SITE>` to :data:`sys.path`.
890
891 .. seealso::
892
893 :pep:`370` -- Per user site-packages directory
894
895
896 .. envvar:: PYTHONUSERBASE
897
898 Defines the :data:`user base directory <site.USER_BASE>`, which is used to
899 compute the path of the :data:`user site-packages directory <site.USER_SITE>`
900 and :ref:`installation paths <sysconfig-user-scheme>` for
901 ``python -m pip install --user``.
902
903 .. seealso::
904
905 :pep:`370` -- Per user site-packages directory
906
907
908 .. envvar:: PYTHONEXECUTABLE
909
910 If this environment variable is set, ``sys.argv[0]`` will be set to its
911 value instead of the value got through the C runtime. Only works on
912 macOS.
913
914 .. envvar:: PYTHONWARNINGS
915
916 This is equivalent to the :option:`-W` option. If set to a comma
917 separated string, it is equivalent to specifying :option:`-W` multiple
918 times, with filters later in the list taking precedence over those earlier
919 in the list.
920
921 The simplest settings apply a particular action unconditionally to all
922 warnings emitted by a process (even those that are otherwise ignored by
923 default)::
924
925 PYTHONWARNINGS=default # Warn once per call location
926 PYTHONWARNINGS=error # Convert to exceptions
927 PYTHONWARNINGS=always # Warn every time
928 PYTHONWARNINGS=all # Same as PYTHONWARNINGS=always
929 PYTHONWARNINGS=module # Warn once per calling module
930 PYTHONWARNINGS=once # Warn once per Python process
931 PYTHONWARNINGS=ignore # Never warn
932
933 See :ref:`warning-filter` and :ref:`describing-warning-filters` for more
934 details.
935
936
937 .. envvar:: PYTHONFAULTHANDLER
938
939 If this environment variable is set to a non-empty string,
940 :func:`faulthandler.enable` is called at startup: install a handler for
941 :const:`~signal.SIGSEGV`, :const:`~signal.SIGFPE`,
942 :const:`~signal.SIGABRT`, :const:`~signal.SIGBUS` and
943 :const:`~signal.SIGILL` signals to dump the Python traceback.
944 This is equivalent to :option:`-X` ``faulthandler`` option.
945
946 .. versionadded:: 3.3
947
948
949 .. envvar:: PYTHONTRACEMALLOC
950
951 If this environment variable is set to a non-empty string, start tracing
952 Python memory allocations using the :mod:`tracemalloc` module. The value of
953 the variable is the maximum number of frames stored in a traceback of a
954 trace. For example, ``PYTHONTRACEMALLOC=1`` stores only the most recent
955 frame.
956 See the :func:`tracemalloc.start` function for more information.
957 This is equivalent to setting the :option:`-X` ``tracemalloc`` option.
958
959 .. versionadded:: 3.4
960
961
962 .. envvar:: PYTHONPROFILEIMPORTTIME
963
964 If this environment variable is set to a non-empty string, Python will
965 show how long each import takes.
966 This is equivalent to setting the :option:`-X` ``importtime`` option.
967
968 .. versionadded:: 3.7
969
970
971 .. envvar:: PYTHONASYNCIODEBUG
972
973 If this environment variable is set to a non-empty string, enable the
974 :ref:`debug mode <asyncio-debug-mode>` of the :mod:`asyncio` module.
975
976 .. versionadded:: 3.4
977
978
979 .. envvar:: PYTHONMALLOC
980
981 Set the Python memory allocators and/or install debug hooks.
982
983 Set the family of memory allocators used by Python:
984
985 * ``default``: use the :ref:`default memory allocators
986 <default-memory-allocators>`.
987 * ``malloc``: use the :c:func:`malloc` function of the C library
988 for all domains (:c:macro:`PYMEM_DOMAIN_RAW`, :c:macro:`PYMEM_DOMAIN_MEM`,
989 :c:macro:`PYMEM_DOMAIN_OBJ`).
990 * ``pymalloc``: use the :ref:`pymalloc allocator <pymalloc>` for
991 :c:macro:`PYMEM_DOMAIN_MEM` and :c:macro:`PYMEM_DOMAIN_OBJ` domains and use
992 the :c:func:`malloc` function for the :c:macro:`PYMEM_DOMAIN_RAW` domain.
993 * ``mimalloc``: use the :ref:`mimalloc allocator <mimalloc>` for
994 :c:macro:`PYMEM_DOMAIN_MEM` and :c:macro:`PYMEM_DOMAIN_OBJ` domains and use
995 the :c:func:`malloc` function for the :c:macro:`PYMEM_DOMAIN_RAW` domain.
996
997 Install :ref:`debug hooks <pymem-debug-hooks>`:
998
999 * ``debug``: install debug hooks on top of the :ref:`default memory
1000 allocators <default-memory-allocators>`.
1001 * ``malloc_debug``: same as ``malloc`` but also install debug hooks.
1002 * ``pymalloc_debug``: same as ``pymalloc`` but also install debug hooks.
1003 * ``mimalloc_debug``: same as ``mimalloc`` but also install debug hooks.
1004
1005 .. versionadded:: 3.6
1006
1007 .. versionchanged:: 3.7
1008 Added the ``"default"`` allocator.
1009
1010
1011 .. envvar:: PYTHONMALLOCSTATS
1012
1013 If set to a non-empty string, Python will print statistics of the
1014 :ref:`pymalloc memory allocator <pymalloc>` every time a new pymalloc object
1015 arena is created, and on shutdown.
1016
1017 This variable is ignored if the :envvar:`PYTHONMALLOC` environment variable
1018 is used to force the :c:func:`malloc` allocator of the C library, or if
1019 Python is configured without ``pymalloc`` support.
1020
1021 .. versionchanged:: 3.6
1022 This variable can now also be used on Python compiled in release mode.
1023 It now has no effect if set to an empty string.
1024
1025
1026 .. envvar:: PYTHONLEGACYWINDOWSFSENCODING
1027
1028 If set to a non-empty string, the default :term:`filesystem encoding and
1029 error handler` mode will revert to their pre-3.6 values of 'mbcs' and
1030 'replace', respectively. Otherwise, the new defaults 'utf-8' and
1031 'surrogatepass' are used.
1032
1033 This may also be enabled at runtime with
1034 :func:`sys._enablelegacywindowsfsencoding`.
1035
1036 .. availability:: Windows.
1037
1038 .. versionadded:: 3.6
1039 See :pep:`529` for more details.
1040
1041 .. envvar:: PYTHONLEGACYWINDOWSSTDIO
1042
1043 If set to a non-empty string, does not use the new console reader and
1044 writer. This means that Unicode characters will be encoded according to
1045 the active console code page, rather than using utf-8.
1046
1047 This variable is ignored if the standard streams are redirected (to files
1048 or pipes) rather than referring to console buffers.
1049
1050 .. availability:: Windows.
1051
1052 .. versionadded:: 3.6
1053
1054
1055 .. envvar:: PYTHONCOERCECLOCALE
1056
1057 If set to the value ``0``, causes the main Python command line application
1058 to skip coercing the legacy ASCII-based C and POSIX locales to a more
1059 capable UTF-8 based alternative.
1060
1061 If this variable is *not* set (or is set to a value other than ``0``), the
1062 ``LC_ALL`` locale override environment variable is also not set, and the
1063 current locale reported for the ``LC_CTYPE`` category is either the default
1064 ``C`` locale, or else the explicitly ASCII-based ``POSIX`` locale, then the
1065 Python CLI will attempt to configure the following locales for the
1066 ``LC_CTYPE`` category in the order listed before loading the interpreter
1067 runtime:
1068
1069 * ``C.UTF-8``
1070 * ``C.utf8``
1071 * ``UTF-8``
1072
1073 If setting one of these locale categories succeeds, then the ``LC_CTYPE``
1074 environment variable will also be set accordingly in the current process
1075 environment before the Python runtime is initialized. This ensures that in
1076 addition to being seen by both the interpreter itself and other locale-aware
1077 components running in the same process (such as the GNU ``readline``
1078 library), the updated setting is also seen in subprocesses (regardless of
1079 whether or not those processes are running a Python interpreter), as well as
1080 in operations that query the environment rather than the current C locale
1081 (such as Python's own :func:`locale.getdefaultlocale`).
1082
1083 Configuring one of these locales (either explicitly or via the above
1084 implicit locale coercion) automatically enables the ``surrogateescape``
1085 :ref:`error handler <error-handlers>` for :data:`sys.stdin` and
1086 :data:`sys.stdout` (:data:`sys.stderr` continues to use ``backslashreplace``
1087 as it does in any other locale). This stream handling behavior can be
1088 overridden using :envvar:`PYTHONIOENCODING` as usual.
1089
1090 For debugging purposes, setting ``PYTHONCOERCECLOCALE=warn`` will cause
1091 Python to emit warning messages on ``stderr`` if either the locale coercion
1092 activates, or else if a locale that *would* have triggered coercion is
1093 still active when the Python runtime is initialized.
1094
1095 Also note that even when locale coercion is disabled, or when it fails to
1096 find a suitable target locale, :envvar:`PYTHONUTF8` will still activate by
1097 default in legacy ASCII-based locales. Both features must be disabled in
1098 order to force the interpreter to use ``ASCII`` instead of ``UTF-8`` for
1099 system interfaces.
1100
1101 .. availability:: Unix.
1102
1103 .. versionadded:: 3.7
1104 See :pep:`538` for more details.
1105
1106
1107 .. envvar:: PYTHONDEVMODE
1108
1109 If this environment variable is set to a non-empty string, enable
1110 :ref:`Python Development Mode <devmode>`, introducing additional runtime
1111 checks that are too expensive to be enabled by default.
1112 This is equivalent to setting the :option:`-X` ``dev`` option.
1113
1114 .. versionadded:: 3.7
1115
1116 .. envvar:: PYTHONUTF8
1117
1118 If set to ``1``, enable the :ref:`Python UTF-8 Mode <utf8-mode>`.
1119
1120 If set to ``0``, disable the :ref:`Python UTF-8 Mode <utf8-mode>`.
1121
1122 Setting any other non-empty string causes an error during interpreter
1123 initialisation.
1124
1125 .. versionadded:: 3.7
1126
1127 .. envvar:: PYTHONWARNDEFAULTENCODING
1128
1129 If this environment variable is set to a non-empty string, issue a
1130 :class:`EncodingWarning` when the locale-specific default encoding is used.
1131
1132 See :ref:`io-encoding-warning` for details.
1133
1134 .. versionadded:: 3.10
1135
1136 .. envvar:: PYTHONNODEBUGRANGES
1137
1138 If this variable is set, it disables the inclusion of the tables mapping
1139 extra location information (end line, start column offset and end column
1140 offset) to every instruction in code objects. This is useful when smaller
1141 code objects and pyc files are desired as well as suppressing the extra visual
1142 location indicators when the interpreter displays tracebacks.
1143
1144 .. versionadded:: 3.11
1145
1146 .. envvar:: PYTHONPERFSUPPORT
1147
1148 If this variable is set to a nonzero value, it enables support for
1149 the Linux ``perf`` profiler so Python calls can be detected by it.
1150
1151 If set to ``0``, disable Linux ``perf`` profiler support.
1152
1153 See also the :option:`-X perf <-X>` command-line option
1154 and :ref:`perf_profiling`.
1155
1156 .. versionadded:: 3.12
1157
1158 .. envvar:: PYTHON_PERF_JIT_SUPPORT
1159
1160 If this variable is set to a nonzero value, it enables support for
1161 the Linux ``perf`` profiler so Python calls can be detected by it
1162 using DWARF information.
1163
1164 If set to ``0``, disable Linux ``perf`` profiler support.
1165
1166 See also the :option:`-X perf_jit <-X>` command-line option
1167 and :ref:`perf_profiling`.
1168
1169 .. versionadded:: 3.13
1170
1171
1172
1173 .. envvar:: PYTHON_CPU_COUNT
1174
1175 If this variable is set to a positive integer, it overrides the return
1176 values of :func:`os.cpu_count` and :func:`os.process_cpu_count`.
1177
1178 See also the :option:`-X cpu_count <-X>` command-line option.
1179
1180 .. versionadded:: 3.13
1181
1182 .. envvar:: PYTHON_FROZEN_MODULES
1183
1184 If this variable is set to ``on`` or ``off``, it determines whether or not
1185 frozen modules are ignored by the import machinery. A value of ``on`` means
1186 they get imported and ``off`` means they are ignored. The default is ``on``
1187 for non-debug builds (the normal case) and ``off`` for debug builds.
1188 Note that the :mod:`!importlib_bootstrap` and
1189 :mod:`!importlib_bootstrap_external` frozen modules are always used, even
1190 if this flag is set to ``off``.
1191
1192 See also the :option:`-X frozen_modules <-X>` command-line option.
1193
1194 .. versionadded:: 3.13
1195
1196 .. envvar:: PYTHON_COLORS
1197
1198 If this variable is set to ``1``, the interpreter will colorize various kinds
1199 of output. Setting it to ``0`` deactivates this behavior.
1200 See also :ref:`using-on-controlling-color`.
1201
1202 .. versionadded:: 3.13
1203
1204 .. envvar:: PYTHON_BASIC_REPL
1205
1206 If this variable is set to any value, the interpreter will not attempt to
1207 load the Python-based :term:`REPL` that requires :mod:`curses` and
1208 :mod:`readline`, and will instead use the traditional parser-based
1209 :term:`REPL`.
1210
1211 .. versionadded:: 3.13
1212
1213 .. envvar:: PYTHON_HISTORY
1214
1215 This environment variable can be used to set the location of a
1216 ``.python_history`` file (by default, it is ``.python_history`` in the
1217 user's home directory).
1218
1219 .. versionadded:: 3.13
1220
1221 .. envvar:: PYTHON_GIL
1222
1223 If this variable is set to ``1``, the global interpreter lock (GIL) will be
1224 forced on. Setting it to ``0`` forces the GIL off (needs Python configured with
1225 the :option:`--disable-gil` build option).
1226
1227 See also the :option:`-X gil <-X>` command-line option, which takes
1228 precedence over this variable, and :ref:`whatsnew313-free-threaded-cpython`.
1229
1230 .. versionadded:: 3.13
1231
1232 .. envvar:: PYTHON_JIT
1233
1234 On builds where experimental just-in-time compilation is available, this
1235 variable can force the JIT to be disabled (``0``) or enabled (``1``) at
1236 interpreter startup.
1237
1238 .. versionadded:: 3.13
1239
1240 Debug-mode variables
1241 ~~~~~~~~~~~~~~~~~~~~
1242
1243 .. envvar:: PYTHONDUMPREFS
1244
1245 If set, Python will dump objects and reference counts still alive after
1246 shutting down the interpreter.
1247
1248 Needs Python configured with the :option:`--with-trace-refs` build option.
1249
1250 .. envvar:: PYTHONDUMPREFSFILE
1251
1252 If set, Python will dump objects and reference counts still alive
1253 after shutting down the interpreter into a file under the path given
1254 as the value to this environment variable.
1255
1256 Needs Python configured with the :option:`--with-trace-refs` build option.
1257
1258 .. versionadded:: 3.11
1259
1260 .. envvar:: PYTHON_PRESITE
1261
1262 If this variable is set to a module, that module will be imported
1263 early in the interpreter lifecycle, before the :mod:`site` module is
1264 executed, and before the :mod:`__main__` module is created.
1265 Therefore, the imported module is not treated as :mod:`__main__`.
1266
1267 This can be used to execute code early during Python initialization.
1268
1269 To import a submodule, use ``package.module`` as the value, like in
1270 an import statement.
1271
1272 See also the :option:`-X presite <-X>` command-line option,
1273 which takes precedence over this variable.
1274
1275 Needs Python configured with the :option:`--with-pydebug` build option.
1276
1277 .. versionadded:: 3.13