3
.. ATTENTION: You probably should update Misc/python.man, too, if you modify
8
Command line and environment
9
============================
11
The CPython interpreter scans the command line and the environment for various
16
Other implementations' command line schemes may differ. See
17
:ref:`implementations` for further resources.
25
When invoking Python, you may specify any of these options::
27
python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]
29
The most common use case is, of course, a simple invocation of a script::
34
.. _using-on-interface-options:
39
The interpreter interface resembles that of the UNIX shell, but provides some
40
additional methods of invocation:
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
* When called with a file name argument or with a file as standard input, it
46
reads and executes a script from that file.
47
* When called with a directory name argument, it reads and executes an
48
appropriately named script from that directory.
49
* When called with ``-c command``, it executes the Python statement(s) given as
50
*command*. Here *command* may contain multiple statements separated by
51
newlines. Leading whitespace is significant in Python statements!
52
* When called with ``-m module-name``, the given module is located on the
53
Python module path and executed as a script.
55
In non-interactive mode, the entire input is parsed before it is executed.
57
An interface option terminates the list of options consumed by the interpreter,
58
all consecutive arguments will end up in :data:`sys.argv` -- note that the first
59
element, subscript zero (``sys.argv[0]``), is a string reflecting the program's
62
.. cmdoption:: -c <command>
64
Execute the Python code in *command*. *command* can be one or more
65
statements separated by newlines, with significant leading whitespace as in
68
If this option is given, the first element of :data:`sys.argv` will be
69
``"-c"`` and the current directory will be added to the start of
70
:data:`sys.path` (allowing modules in that directory to be imported as top
74
.. cmdoption:: -m <module-name>
76
Search :data:`sys.path` for the named module and execute its contents as
77
the :mod:`__main__` module.
79
Since the argument is a *module* name, you must not give a file extension
80
(``.py``). The module name should be a valid absolute Python module name, but
81
the implementation may not always enforce this (e.g. it may allow you to
82
use a name that includes a hyphen).
84
Package names (including namespace packages) are also permitted. When a
85
package name is supplied instead
86
of a normal module, the interpreter will execute ``<pkg>.__main__`` as
87
the main module. This behaviour is deliberately similar to the handling
88
of directories and zipfiles that are passed to the interpreter as the
93
This option cannot be used with built-in modules and extension modules
94
written in C, since they do not have Python module files. However, it
95
can still be used for precompiled modules, even if the original source
96
file is not available.
98
If this option is given, the first element of :data:`sys.argv` will be the
99
full path to the module file (while the module file is being located, the
100
first element will be set to ``"-m"``). As with the :option:`-c` option,
101
the current directory will be added to the start of :data:`sys.path`.
103
Many standard library modules contain code that is invoked on their execution
104
as a script. An example is the :mod:`timeit` module::
106
python -mtimeit -s 'setup here' 'benchmarked code here'
107
python -mtimeit -h # for details
110
:func:`runpy.run_module`
111
Equivalent functionality directly available to Python code
113
:pep:`338` -- Executing modules as scripts
116
.. versionchanged:: 3.1
117
Supply the package name to run a ``__main__`` submodule.
119
.. versionchanged:: 3.4
120
namespace packages are also supported
125
Read commands from standard input (:data:`sys.stdin`). If standard input is
126
a terminal, :option:`-i` is implied.
128
If this option is given, the first element of :data:`sys.argv` will be
129
``"-"`` and the current directory will be added to the start of
133
.. describe:: <script>
135
Execute the Python code contained in *script*, which must be a filesystem
136
path (absolute or relative) referring to either a Python file, a directory
137
containing a ``__main__.py`` file, or a zipfile containing a
138
``__main__.py`` file.
140
If this option is given, the first element of :data:`sys.argv` will be the
141
script name as given on the command line.
143
If the script name refers directly to a Python file, the directory
144
containing that file is added to the start of :data:`sys.path`, and the
145
file is executed as the :mod:`__main__` module.
147
If the script name refers to a directory or zipfile, the script name is
148
added to the start of :data:`sys.path` and the ``__main__.py`` file in
149
that location is executed as the :mod:`__main__` module.
152
:func:`runpy.run_path`
153
Equivalent functionality directly available to Python code
156
If no interface option is given, :option:`-i` is implied, ``sys.argv[0]`` is
157
an empty string (``""``) and the current directory will be added to the
158
start of :data:`sys.path`. Also, tab-completion and history editing is
159
automatically enabled, if available on your platform (see
160
:ref:`rlcompleter-config`).
162
.. seealso:: :ref:`tut-invoking`
164
.. versionchanged:: 3.4
165
Automatic enabling of tab-completion and history editing.
175
Print a short description of all command line options.
181
Print the Python version number and exit. Example output could be::
186
.. _using-on-misc-options:
188
Miscellaneous options
189
~~~~~~~~~~~~~~~~~~~~~
193
Issue a warning when comparing :class:`bytes` or :class:`bytearray` with
194
:class:`str` or :class:`bytes` with :class:`int`. Issue an error when the
195
option is given twice (:option:`-bb`).
197
.. versionchanged: 3.5
198
Affects comparisons of :class:`bytes` with :class:`int`.
202
If given, Python won't try to write ``.pyc`` files on the
203
import of source modules. See also :envvar:`PYTHONDONTWRITEBYTECODE`.
208
Turn on parser debugging output (for wizards only, depending on compilation
209
options). See also :envvar:`PYTHONDEBUG`.
214
Ignore all :envvar:`PYTHON*` environment variables, e.g.
215
:envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
220
When a script is passed as first argument or the :option:`-c` option is used,
221
enter interactive mode after executing the script or the command, even when
222
:data:`sys.stdin` does not appear to be a terminal. The
223
:envvar:`PYTHONSTARTUP` file is not read.
225
This can be useful to inspect global variables or a stack trace when a script
226
raises an exception. See also :envvar:`PYTHONINSPECT`.
231
Run Python in isolated mode. This also implies -E and -s.
232
In isolated mode :data:`sys.path` contains neither the script's directory nor
233
the user's site-packages directory. All :envvar:`PYTHON*` environment
234
variables are ignored, too. Further restrictions may be imposed to prevent
235
the user from injecting malicious code.
237
.. versionadded:: 3.4
242
Turn on basic optimizations. This changes the filename extension for
243
compiled (:term:`bytecode`) files from ``.pyc`` to ``.pyo``. See also
244
:envvar:`PYTHONOPTIMIZE`.
249
Discard docstrings in addition to the :option:`-O` optimizations.
254
Don't display the copyright and version messages even in interactive mode.
256
.. versionadded:: 3.2
261
Kept for compatibility. On Python 3.3 and greater, hash randomization is
262
turned on by default.
264
On previous versions of Python, this option turns on hash randomization,
265
so that the :meth:`__hash__` values of str, bytes and datetime
266
are "salted" with an unpredictable random value. Although they remain
267
constant within an individual Python process, they are not predictable
268
between repeated invocations of Python.
270
Hash randomization is intended to provide protection against a
271
denial-of-service caused by carefully-chosen inputs that exploit the worst
272
case performance of a dict construction, O(n^2) complexity. See
273
http://www.ocert.org/advisories/ocert-2011-003.html for details.
275
:envvar:`PYTHONHASHSEED` allows you to set a fixed value for the hash
278
.. versionadded:: 3.2.3
283
Don't add the :data:`user site-packages directory <site.USER_SITE>` to
288
:pep:`370` -- Per user site-packages directory
293
Disable the import of the module :mod:`site` and the site-dependent
294
manipulations of :data:`sys.path` that it entails. Also disable these
295
manipulations if :mod:`site` is explicitly imported later (call
296
:func:`site.main` if you want them to be triggered).
301
Force the binary layer of the stdout and stderr streams (which is
302
available as their ``buffer`` attribute) to be unbuffered. The text I/O
303
layer will still be line-buffered if writing to the console, or
304
block-buffered if redirected to a non-interactive file.
306
See also :envvar:`PYTHONUNBUFFERED`.
311
Print a message each time a module is initialized, showing the place
312
(filename or built-in module) from which it is loaded. When given twice
313
(:option:`-vv`), print a message for each file that is checked for when
314
searching for a module. Also provides information on module cleanup at exit.
315
See also :envvar:`PYTHONVERBOSE`.
318
.. cmdoption:: -W arg
320
Warning control. Python's warning machinery by default prints warning
321
messages to :data:`sys.stderr`. A typical warning message has the following
324
file:line: category: message
326
By default, each warning is printed once for each source line where it
327
occurs. This option controls how often warnings are printed.
329
Multiple :option:`-W` options may be given; when a warning matches more than
330
one option, the action for the last matching option is performed. Invalid
331
:option:`-W` options are ignored (though, a warning message is printed about
332
invalid options when the first warning is issued).
334
Warnings can also be controlled from within a Python program using the
335
:mod:`warnings` module.
337
The simplest form of argument is one of the following action strings (or a
338
unique abbreviation):
343
Explicitly request the default behavior (printing each warning once per
346
Print a warning each time it occurs (this may generate many messages if a
347
warning is triggered repeatedly for the same source line, such as inside a
350
Print each warning only the first time it occurs in each module.
352
Print each warning only the first time it occurs in the program.
354
Raise an exception instead of printing a warning message.
356
The full form of argument is::
358
action:message:category:module:line
360
Here, *action* is as explained above but only applies to messages that match
361
the remaining fields. Empty fields match all values; trailing empty fields
362
may be omitted. The *message* field matches the start of the warning message
363
printed; this match is case-insensitive. The *category* field matches the
364
warning category. This must be a class name; the match tests whether the
365
actual warning category of the message is a subclass of the specified warning
366
category. The full class name must be given. The *module* field matches the
367
(fully-qualified) module name; this match is case-sensitive. The *line*
368
field matches the line number, where zero matches all line numbers and is
369
thus equivalent to an omitted line number.
372
:mod:`warnings` -- the warnings module
374
:pep:`230` -- Warning framework
376
:envvar:`PYTHONWARNINGS`
381
Skip the first line of the source, allowing use of non-Unix forms of
382
``#!cmd``. This is intended for a DOS specific hack only.
384
.. note:: The line numbers in error messages will be off by one.
389
Reserved for various implementation-specific options. CPython currently
390
defines the following possible values:
392
* ``-X faulthandler`` to enable :mod:`faulthandler`;
393
* ``-X showrefcount`` to enable the output of the total reference count
394
and memory blocks (only works on debug builds);
395
* ``-X tracemalloc`` to start tracing Python memory allocations using the
396
:mod:`tracemalloc` module. By default, only the most recent frame is
397
stored in a traceback of a trace. Use ``-X tracemalloc=NFRAME`` to start
398
tracing with a traceback limit of *NFRAME* frames. See the
399
:func:`tracemalloc.start` for more information.
401
It also allows passing arbitrary values and retrieving them through the
402
:data:`sys._xoptions` dictionary.
404
.. versionchanged:: 3.2
405
It is now allowed to pass :option:`-X` with CPython.
407
.. versionadded:: 3.3
408
The ``-X faulthandler`` option.
410
.. versionadded:: 3.4
411
The ``-X showrefcount`` and ``-X tracemalloc`` options.
414
Options you shouldn't use
415
~~~~~~~~~~~~~~~~~~~~~~~~~
419
Reserved for use by Jython_.
421
.. _Jython: http://www.jython.org/
424
.. _using-on-envvars:
426
Environment variables
427
---------------------
429
These environment variables influence Python's behavior, they are processed
430
before the command-line switches other than -E or -I. It is customary that
431
command-line switches override environmental variables where there is a
434
.. envvar:: PYTHONHOME
436
Change the location of the standard Python libraries. By default, the
437
libraries are searched in :file:`{prefix}/lib/python{version}` and
438
:file:`{exec_prefix}/lib/python{version}`, where :file:`{prefix}` and
439
:file:`{exec_prefix}` are installation-dependent directories, both defaulting
440
to :file:`/usr/local`.
442
When :envvar:`PYTHONHOME` is set to a single directory, its value replaces
443
both :file:`{prefix}` and :file:`{exec_prefix}`. To specify different values
444
for these, set :envvar:`PYTHONHOME` to :file:`{prefix}:{exec_prefix}`.
447
.. envvar:: PYTHONPATH
449
Augment the default search path for module files. The format is the same as
450
the shell's :envvar:`PATH`: one or more directory pathnames separated by
451
:data:`os.pathsep` (e.g. colons on Unix or semicolons on Windows).
452
Non-existent directories are silently ignored.
454
In addition to normal directories, individual :envvar:`PYTHONPATH` entries
455
may refer to zipfiles containing pure Python modules (in either source or
456
compiled form). Extension modules cannot be imported from zipfiles.
458
The default search path is installation dependent, but generally begins with
459
:file:`{prefix}/lib/python{version}` (see :envvar:`PYTHONHOME` above). It
460
is *always* appended to :envvar:`PYTHONPATH`.
462
An additional directory will be inserted in the search path in front of
463
:envvar:`PYTHONPATH` as described above under
464
:ref:`using-on-interface-options`. The search path can be manipulated from
465
within a Python program as the variable :data:`sys.path`.
468
.. envvar:: PYTHONSTARTUP
470
If this is the name of a readable file, the Python commands in that file are
471
executed before the first prompt is displayed in interactive mode. The file
472
is executed in the same namespace where interactive commands are executed so
473
that objects defined or imported in it can be used without qualification in
474
the interactive session. You can also change the prompts :data:`sys.ps1` and
475
:data:`sys.ps2` and the hook :data:`sys.__interactivehook__` in this file.
478
.. envvar:: PYTHONOPTIMIZE
480
If this is set to a non-empty string it is equivalent to specifying the
481
:option:`-O` option. If set to an integer, it is equivalent to specifying
482
:option:`-O` multiple times.
485
.. envvar:: PYTHONDEBUG
487
If this is set to a non-empty string it is equivalent to specifying the
488
:option:`-d` option. If set to an integer, it is equivalent to specifying
489
:option:`-d` multiple times.
492
.. envvar:: PYTHONINSPECT
494
If this is set to a non-empty string it is equivalent to specifying the
497
This variable can also be modified by Python code using :data:`os.environ`
498
to force inspect mode on program termination.
501
.. envvar:: PYTHONUNBUFFERED
503
If this is set to a non-empty string it is equivalent to specifying the
507
.. envvar:: PYTHONVERBOSE
509
If this is set to a non-empty string it is equivalent to specifying the
510
:option:`-v` option. If set to an integer, it is equivalent to specifying
511
:option:`-v` multiple times.
514
.. envvar:: PYTHONCASEOK
516
If this is set, Python ignores case in :keyword:`import` statements. This
517
only works on Windows and OS X.
520
.. envvar:: PYTHONDONTWRITEBYTECODE
522
If this is set to a non-empty string, Python won't try to write ``.pyc`` or
523
``.pyo`` files on the import of source modules. This is equivalent to
524
specifying the :option:`-B` option.
527
.. envvar:: PYTHONHASHSEED
529
If this variable is not set or set to ``random``, a random value is used
530
to seed the hashes of str, bytes and datetime objects.
532
If :envvar:`PYTHONHASHSEED` is set to an integer value, it is used as a fixed
533
seed for generating the hash() of the types covered by the hash
536
Its purpose is to allow repeatable hashing, such as for selftests for the
537
interpreter itself, or to allow a cluster of python processes to share hash
540
The integer must be a decimal number in the range [0,4294967295]. Specifying
541
the value 0 will disable hash randomization.
543
.. versionadded:: 3.2.3
546
.. envvar:: PYTHONIOENCODING
548
If this is set before running the interpreter, it overrides the encoding used
549
for stdin/stdout/stderr, in the syntax ``encodingname:errorhandler``. Both
550
the ``encodingname`` and the ``:errorhandler`` parts are optional and have
551
the same meaning as in :func:`str.encode`.
553
For stderr, the ``:errorhandler`` part is ignored; the handler will always be
554
``'backslashreplace'``.
556
.. versionchanged:: 3.4
557
The ``encodingname`` part is now optional.
560
.. envvar:: PYTHONNOUSERSITE
562
If this is set, Python won't add the :data:`user site-packages directory
563
<site.USER_SITE>` to :data:`sys.path`.
567
:pep:`370` -- Per user site-packages directory
570
.. envvar:: PYTHONUSERBASE
572
Defines the :data:`user base directory <site.USER_BASE>`, which is used to
573
compute the path of the :data:`user site-packages directory <site.USER_SITE>`
574
and :ref:`Distutils installation paths <inst-alt-install-user>` for
575
``python setup.py install --user``.
579
:pep:`370` -- Per user site-packages directory
582
.. envvar:: PYTHONEXECUTABLE
584
If this environment variable is set, ``sys.argv[0]`` will be set to its
585
value instead of the value got through the C runtime. Only works on
588
.. envvar:: PYTHONWARNINGS
590
This is equivalent to the :option:`-W` option. If set to a comma
591
separated string, it is equivalent to specifying :option:`-W` multiple
594
.. envvar:: PYTHONFAULTHANDLER
596
If this environment variable is set to a non-empty string,
597
:func:`faulthandler.enable` is called at startup: install a handler for
598
:const:`SIGSEGV`, :const:`SIGFPE`, :const:`SIGABRT`, :const:`SIGBUS` and
599
:const:`SIGILL` signals to dump the Python traceback. This is equivalent to
600
:option:`-X` ``faulthandler`` option.
602
.. versionadded:: 3.3
605
.. envvar:: PYTHONTRACEMALLOC
607
If this environment variable is set to a non-empty string, start tracing
608
Python memory allocations using the :mod:`tracemalloc` module. The value of
609
the variable is the maximum number of frames stored in a traceback of a
610
trace. For example, ``PYTHONTRACEMALLOC=1`` stores only the most recent
611
frame. See the :func:`tracemalloc.start` for more information.
613
.. versionadded:: 3.4
616
.. envvar:: PYTHONASYNCIODEBUG
618
If this environment variable is set to a non-empty string, enable the
619
:ref:`debug mode <asyncio-debug-mode>` of the :mod:`asyncio` module.
621
.. versionadded:: 3.4
627
Setting these variables only has an effect in a debug build of Python, that is,
628
if Python was configured with the ``--with-pydebug`` build option.
630
.. envvar:: PYTHONTHREADDEBUG
632
If set, Python will print threading debug info.
635
.. envvar:: PYTHONDUMPREFS
637
If set, Python will dump objects and reference counts still alive after
638
shutting down the interpreter.
641
.. envvar:: PYTHONMALLOCSTATS
643
If set, Python will print memory allocation statistics every time a new
644
object arena is created, and on shutdown.