source: python/trunk/Doc/using/cmdline.rst

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

  • Property svn:eol-style set to native
File size: 20.7 KB
RevLine 
[2]1.. highlightlang:: none
2
[391]3.. ATTENTION: You probably should update Misc/python.man, too, if you modify
4.. this file.
5
[2]6.. _using-on-general:
7
8Command line and environment
9============================
10
11The CPython interpreter scans the command line and the environment for various
12settings.
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
22Command line
23------------
24
25When invoking Python, you may specify any of these options::
26
[391]27 python [-BdEiOQsRStuUvVWxX3?] [-c command | -m module-name | script | - ] [args]
[2]28
29The 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
36Interface options
37~~~~~~~~~~~~~~~~~
38
39The interpreter interface resembles that of the UNIX shell, but provides some
40additional 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 *Ctrl-D* on UNIX or *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.
54
55In non-interactive mode, the entire input is parsed before it is executed.
56
57An interface option terminates the list of options consumed by the interpreter,
58all consecutive arguments will end up in :data:`sys.argv` -- note that the first
59element, subscript zero (``sys.argv[0]``), is a string reflecting the program's
60source.
61
62.. cmdoption:: -c <command>
63
[391]64 Execute the Python code in *command*. *command* can be one or more
[2]65 statements separated by newlines, with significant leading whitespace as in
66 normal module code.
67
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
71 level modules).
72
73
74.. cmdoption:: -m <module-name>
75
76 Search :data:`sys.path` for the named module and execute its contents as
77 the :mod:`__main__` module.
78
79 Since the argument is a *module* name, you must not give a file extension
80 (``.py``). The ``module-name`` should be a valid 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).
83
[391]84 Package names are also permitted. When a package name is supplied instead
85 of a normal module, the interpreter will execute ``<pkg>.__main__`` as
86 the main module. This behaviour is deliberately similar to the handling
87 of directories and zipfiles that are passed to the interpreter as the
88 script argument.
89
[2]90 .. note::
91
92 This option cannot be used with built-in modules and extension modules
93 written in C, since they do not have Python module files. However, it
94 can still be used for precompiled modules, even if the original source
95 file is not available.
96
97 If this option is given, the first element of :data:`sys.argv` will be the
98 full path to the module file. As with the :option:`-c` option, the current
99 directory will be added to the start of :data:`sys.path`.
100
101 Many standard library modules contain code that is invoked on their execution
102 as a script. An example is the :mod:`timeit` module::
103
104 python -mtimeit -s 'setup here' 'benchmarked code here'
105 python -mtimeit -h # for details
106
107 .. seealso::
108 :func:`runpy.run_module`
[391]109 Equivalent functionality directly available to Python code
[2]110
111 :pep:`338` -- Executing modules as scripts
112
113 .. versionadded:: 2.4
114
115 .. versionchanged:: 2.5
116 The named module can now be located inside a package.
117
[391]118 .. versionchanged:: 2.7
119 Supply the package name to run a ``__main__`` submodule.
120 sys.argv[0] is now set to ``"-m"`` while searching for the module
121 (it was previously incorrectly set to ``"-c"``)
[2]122
[391]123
[2]124.. describe:: -
125
126 Read commands from standard input (:data:`sys.stdin`). If standard input is
127 a terminal, :option:`-i` is implied.
128
129 If this option is given, the first element of :data:`sys.argv` will be
130 ``"-"`` and the current directory will be added to the start of
131 :data:`sys.path`.
132
133
134.. describe:: <script>
135
136 Execute the Python code contained in *script*, which must be a filesystem
137 path (absolute or relative) referring to either a Python file, a directory
138 containing a ``__main__.py`` file, or a zipfile containing a
139 ``__main__.py`` file.
140
141 If this option is given, the first element of :data:`sys.argv` will be the
142 script name as given on the command line.
143
144 If the script name refers directly to a Python file, the directory
145 containing that file is added to the start of :data:`sys.path`, and the
146 file is executed as the :mod:`__main__` module.
147
148 If the script name refers to a directory or zipfile, the script name is
149 added to the start of :data:`sys.path` and the ``__main__.py`` file in
150 that location is executed as the :mod:`__main__` module.
151
152 .. versionchanged:: 2.5
153 Directories and zipfiles containing a ``__main__.py`` file at the top
154 level are now considered valid Python scripts.
155
156If no interface option is given, :option:`-i` is implied, ``sys.argv[0]`` is
157an empty string (``""``) and the current directory will be added to the
158start of :data:`sys.path`.
159
160.. seealso:: :ref:`tut-invoking`
161
162
163Generic options
164~~~~~~~~~~~~~~~
165
166.. cmdoption:: -?
167 -h
168 --help
169
170 Print a short description of all command line options.
171
172 .. versionchanged:: 2.5
173 The ``--help`` variant.
174
175
176.. cmdoption:: -V
177 --version
178
179 Print the Python version number and exit. Example output could be::
180
181 Python 2.5.1
182
183 .. versionchanged:: 2.5
184 The ``--version`` variant.
185
186
187Miscellaneous options
188~~~~~~~~~~~~~~~~~~~~~
189
190.. cmdoption:: -B
191
192 If given, Python won't try to write ``.pyc`` or ``.pyo`` files on the
193 import of source modules. See also :envvar:`PYTHONDONTWRITEBYTECODE`.
194
195 .. versionadded:: 2.6
196
197
198.. cmdoption:: -d
199
200 Turn on parser debugging output (for wizards only, depending on compilation
201 options). See also :envvar:`PYTHONDEBUG`.
202
203
204.. cmdoption:: -E
205
206 Ignore all :envvar:`PYTHON*` environment variables, e.g.
207 :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
208
209 .. versionadded:: 2.2
210
211
212.. cmdoption:: -i
213
214 When a script is passed as first argument or the :option:`-c` option is used,
215 enter interactive mode after executing the script or the command, even when
216 :data:`sys.stdin` does not appear to be a terminal. The
217 :envvar:`PYTHONSTARTUP` file is not read.
218
219 This can be useful to inspect global variables or a stack trace when a script
220 raises an exception. See also :envvar:`PYTHONINSPECT`.
221
222
223.. cmdoption:: -O
224
225 Turn on basic optimizations. This changes the filename extension for
226 compiled (:term:`bytecode`) files from ``.pyc`` to ``.pyo``. See also
227 :envvar:`PYTHONOPTIMIZE`.
228
229
230.. cmdoption:: -OO
231
232 Discard docstrings in addition to the :option:`-O` optimizations.
233
234
235.. cmdoption:: -Q <arg>
236
237 Division control. The argument must be one of the following:
238
239 ``old``
240 division of int/int and long/long return an int or long (*default*)
241 ``new``
242 new division semantics, i.e. division of int/int and long/long returns a
243 float
244 ``warn``
245 old division semantics with a warning for int/int and long/long
246 ``warnall``
247 old division semantics with a warning for all uses of the division operator
248
249 .. seealso::
250 :file:`Tools/scripts/fixdiv.py`
251 for a use of ``warnall``
252
253 :pep:`238` -- Changing the division operator
254
255
[391]256.. cmdoption:: -R
257
258 Turn on hash randomization, so that the :meth:`__hash__` values of str,
259 bytes and datetime objects are "salted" with an unpredictable random value.
260 Although they remain constant within an individual Python process, they are
261 not predictable between repeated invocations of Python.
262
263 This is intended to provide protection against a denial-of-service caused by
264 carefully-chosen inputs that exploit the worst case performance of a dict
265 construction, O(n^2) complexity. See
266 http://www.ocert.org/advisories/ocert-2011-003.html for details.
267
268 Changing hash values affects the order in which keys are retrieved from a
269 dict. Although Python has never made guarantees about this ordering (and it
270 typically varies between 32-bit and 64-bit builds), enough real-world code
271 implicitly relies on this non-guaranteed behavior that the randomization is
272 disabled by default.
273
274 See also :envvar:`PYTHONHASHSEED`.
275
276 .. versionadded:: 2.6.8
277
278
[2]279.. cmdoption:: -s
280
[391]281 Don't add the :data:`user site-packages directory <site.USER_SITE>` to
282 :data:`sys.path`.
[2]283
284 .. versionadded:: 2.6
285
286 .. seealso::
287
288 :pep:`370` -- Per user site-packages directory
289
290
291.. cmdoption:: -S
292
293 Disable the import of the module :mod:`site` and the site-dependent
294 manipulations of :data:`sys.path` that it entails.
295
296
297.. cmdoption:: -t
298
299 Issue a warning when a source file mixes tabs and spaces for indentation in a
300 way that makes it depend on the worth of a tab expressed in spaces. Issue an
301 error when the option is given twice (:option:`-tt`).
302
303
304.. cmdoption:: -u
305
306 Force stdin, stdout and stderr to be totally unbuffered. On systems where it
307 matters, also put stdin, stdout and stderr in binary mode.
308
309 Note that there is internal buffering in :meth:`file.readlines` and
310 :ref:`bltin-file-objects` (``for line in sys.stdin``) which is not influenced
311 by this option. To work around this, you will want to use
312 :meth:`file.readline` inside a ``while 1:`` loop.
313
314 See also :envvar:`PYTHONUNBUFFERED`.
315
316
317.. cmdoption:: -v
318
319 Print a message each time a module is initialized, showing the place
320 (filename or built-in module) from which it is loaded. When given twice
321 (:option:`-vv`), print a message for each file that is checked for when
322 searching for a module. Also provides information on module cleanup at exit.
323 See also :envvar:`PYTHONVERBOSE`.
324
325
326.. cmdoption:: -W arg
327
328 Warning control. Python's warning machinery by default prints warning
329 messages to :data:`sys.stderr`. A typical warning message has the following
330 form::
331
332 file:line: category: message
333
334 By default, each warning is printed once for each source line where it
335 occurs. This option controls how often warnings are printed.
336
337 Multiple :option:`-W` options may be given; when a warning matches more than
338 one option, the action for the last matching option is performed. Invalid
339 :option:`-W` options are ignored (though, a warning message is printed about
340 invalid options when the first warning is issued).
341
[391]342 Starting from Python 2.7, :exc:`DeprecationWarning` and its descendants
343 are ignored by default. The :option:`-Wd` option can be used to re-enable
344 them.
345
[2]346 Warnings can also be controlled from within a Python program using the
347 :mod:`warnings` module.
348
349 The simplest form of argument is one of the following action strings (or a
350 unique abbreviation) by themselves:
351
352 ``ignore``
353 Ignore all warnings.
354 ``default``
355 Explicitly request the default behavior (printing each warning once per
356 source line).
357 ``all``
358 Print a warning each time it occurs (this may generate many messages if a
359 warning is triggered repeatedly for the same source line, such as inside a
360 loop).
361 ``module``
362 Print each warning only the first time it occurs in each module.
363 ``once``
364 Print each warning only the first time it occurs in the program.
365 ``error``
366 Raise an exception instead of printing a warning message.
367
368 The full form of argument is::
369
370 action:message:category:module:line
371
372 Here, *action* is as explained above but only applies to messages that match
373 the remaining fields. Empty fields match all values; trailing empty fields
374 may be omitted. The *message* field matches the start of the warning message
375 printed; this match is case-insensitive. The *category* field matches the
[391]376 warning category. This must be a class name; the match tests whether the
[2]377 actual warning category of the message is a subclass of the specified warning
378 category. The full class name must be given. The *module* field matches the
379 (fully-qualified) module name; this match is case-sensitive. The *line*
380 field matches the line number, where zero matches all line numbers and is
381 thus equivalent to an omitted line number.
382
383 .. seealso::
384 :mod:`warnings` -- the warnings module
385
386 :pep:`230` -- Warning framework
387
[391]388 :envvar:`PYTHONWARNINGS`
[2]389
[391]390
[2]391.. cmdoption:: -x
392
393 Skip the first line of the source, allowing use of non-Unix forms of
394 ``#!cmd``. This is intended for a DOS specific hack only.
395
396 .. note:: The line numbers in error messages will be off by one.
397
398.. cmdoption:: -3
399
400 Warn about Python 3.x incompatibilities which cannot be fixed trivially by
401 :ref:`2to3 <2to3-reference>`. Among these are:
402
403 * :meth:`dict.has_key`
404 * :func:`apply`
405 * :func:`callable`
406 * :func:`coerce`
407 * :func:`execfile`
408 * :func:`reduce`
409 * :func:`reload`
410
411 Using these will emit a :exc:`DeprecationWarning`.
412
413 .. versionadded:: 2.6
414
415Options you shouldn't use
416~~~~~~~~~~~~~~~~~~~~~~~~~
417
418.. cmdoption:: -J
419
420 Reserved for use by Jython_.
421
422.. _Jython: http://jython.org
423
424.. cmdoption:: -U
425
426 Turns all string literals into unicodes globally. Do not be tempted to use
427 this option as it will probably break your world. It also produces
428 ``.pyc`` files with a different magic number than normal. Instead, you can
429 enable unicode literals on a per-module basis by using::
430
431 from __future__ import unicode_literals
432
433 at the top of the file. See :mod:`__future__` for details.
434
435.. cmdoption:: -X
436
437 Reserved for alternative implementations of Python to use for their own
438 purposes.
439
440.. _using-on-envvars:
441
442Environment variables
443---------------------
444
[391]445These environment variables influence Python's behavior, they are processed
446before the command-line switches other than -E. It is customary that
447command-line switches override environmental variables where there is a
448conflict.
[2]449
450.. envvar:: PYTHONHOME
451
452 Change the location of the standard Python libraries. By default, the
453 libraries are searched in :file:`{prefix}/lib/python{version}` and
454 :file:`{exec_prefix}/lib/python{version}`, where :file:`{prefix}` and
455 :file:`{exec_prefix}` are installation-dependent directories, both defaulting
456 to :file:`/usr/local`.
457
458 When :envvar:`PYTHONHOME` is set to a single directory, its value replaces
459 both :file:`{prefix}` and :file:`{exec_prefix}`. To specify different values
460 for these, set :envvar:`PYTHONHOME` to :file:`{prefix}:{exec_prefix}`.
461
462
463.. envvar:: PYTHONPATH
464
465 Augment the default search path for module files. The format is the same as
466 the shell's :envvar:`PATH`: one or more directory pathnames separated by
467 :data:`os.pathsep` (e.g. colons on Unix or semicolons on Windows).
468 Non-existent directories are silently ignored.
469
470 In addition to normal directories, individual :envvar:`PYTHONPATH` entries
471 may refer to zipfiles containing pure Python modules (in either source or
472 compiled form). Extension modules cannot be imported from zipfiles.
473
474 The default search path is installation dependent, but generally begins with
475 :file:`{prefix}/lib/python{version}` (see :envvar:`PYTHONHOME` above). It
476 is *always* appended to :envvar:`PYTHONPATH`.
477
478 An additional directory will be inserted in the search path in front of
479 :envvar:`PYTHONPATH` as described above under
480 :ref:`using-on-interface-options`. The search path can be manipulated from
481 within a Python program as the variable :data:`sys.path`.
482
483
484.. envvar:: PYTHONSTARTUP
485
486 If this is the name of a readable file, the Python commands in that file are
487 executed before the first prompt is displayed in interactive mode. The file
488 is executed in the same namespace where interactive commands are executed so
489 that objects defined or imported in it can be used without qualification in
490 the interactive session. You can also change the prompts :data:`sys.ps1` and
491 :data:`sys.ps2` in this file.
492
493
494.. envvar:: PYTHONY2K
495
496 Set this to a non-empty string to cause the :mod:`time` module to require
497 dates specified as strings to include 4-digit years, otherwise 2-digit years
498 are converted based on rules described in the :mod:`time` module
499 documentation.
500
501
502.. envvar:: PYTHONOPTIMIZE
503
504 If this is set to a non-empty string it is equivalent to specifying the
505 :option:`-O` option. If set to an integer, it is equivalent to specifying
506 :option:`-O` multiple times.
507
508
509.. envvar:: PYTHONDEBUG
510
511 If this is set to a non-empty string it is equivalent to specifying the
512 :option:`-d` option. If set to an integer, it is equivalent to specifying
513 :option:`-d` multiple times.
514
515
516.. envvar:: PYTHONINSPECT
517
518 If this is set to a non-empty string it is equivalent to specifying the
519 :option:`-i` option.
520
521 This variable can also be modified by Python code using :data:`os.environ`
522 to force inspect mode on program termination.
523
524
525.. envvar:: PYTHONUNBUFFERED
526
527 If this is set to a non-empty string it is equivalent to specifying the
528 :option:`-u` option.
529
530
531.. envvar:: PYTHONVERBOSE
532
533 If this is set to a non-empty string it is equivalent to specifying the
534 :option:`-v` option. If set to an integer, it is equivalent to specifying
535 :option:`-v` multiple times.
536
537
538.. envvar:: PYTHONCASEOK
539
540 If this is set, Python ignores case in :keyword:`import` statements. This
[391]541 only works on Windows, OS X, OS/2, and RiscOS.
[2]542
543
544.. envvar:: PYTHONDONTWRITEBYTECODE
545
546 If this is set, Python won't try to write ``.pyc`` or ``.pyo`` files on the
[391]547 import of source modules. This is equivalent to specifying the :option:`-B`
548 option.
[2]549
550 .. versionadded:: 2.6
551
[391]552.. envvar:: PYTHONHASHSEED
553
554 If this variable is set to ``random``, the effect is the same as specifying
555 the :option:`-R` option: a random value is used to seed the hashes of str,
556 bytes and datetime objects.
557
558 If :envvar:`PYTHONHASHSEED` is set to an integer value, it is used as a
559 fixed seed for generating the hash() of the types covered by the hash
560 randomization.
561
562 Its purpose is to allow repeatable hashing, such as for selftests for the
563 interpreter itself, or to allow a cluster of python processes to share hash
564 values.
565
566 The integer must be a decimal number in the range [0,4294967295].
567 Specifying the value 0 will lead to the same hash values as when hash
568 randomization is disabled.
569
570 .. versionadded:: 2.6.8
571
572
[2]573.. envvar:: PYTHONIOENCODING
574
575 Overrides the encoding used for stdin/stdout/stderr, in the syntax
576 ``encodingname:errorhandler``. The ``:errorhandler`` part is optional and
577 has the same meaning as in :func:`str.encode`.
578
579 .. versionadded:: 2.6
580
581
582.. envvar:: PYTHONNOUSERSITE
583
[391]584 If this is set, Python won't add the :data:`user site-packages directory
585 <site.USER_SITE>` to :data:`sys.path`.
[2]586
587 .. versionadded:: 2.6
588
589 .. seealso::
590
591 :pep:`370` -- Per user site-packages directory
592
593
594.. envvar:: PYTHONUSERBASE
595
[391]596 Defines the :data:`user base directory <site.USER_BASE>`, which is used to
597 compute the path of the :data:`user site-packages directory <site.USER_SITE>`
598 and :ref:`Distutils installation paths <inst-alt-install-user>` for ``python
599 setup.py install --user``.
[2]600
601 .. versionadded:: 2.6
602
603 .. seealso::
604
605 :pep:`370` -- Per user site-packages directory
606
607
608.. envvar:: PYTHONEXECUTABLE
609
610 If this environment variable is set, ``sys.argv[0]`` will be set to its
611 value instead of the value got through the C runtime. Only works on
612 Mac OS X.
613
[391]614.. envvar:: PYTHONWARNINGS
[2]615
[391]616 This is equivalent to the :option:`-W` option. If set to a comma
617 separated string, it is equivalent to specifying :option:`-W` multiple
618 times.
619
620
[2]621Debug-mode variables
622~~~~~~~~~~~~~~~~~~~~
623
624Setting these variables only has an effect in a debug build of Python, that is,
[391]625if Python was configured with the ``--with-pydebug`` build option.
[2]626
627.. envvar:: PYTHONTHREADDEBUG
628
629 If set, Python will print threading debug info.
630
631 .. versionchanged:: 2.6
632 Previously, this variable was called ``THREADDEBUG``.
633
634.. envvar:: PYTHONDUMPREFS
635
636 If set, Python will dump objects and reference counts still alive after
637 shutting down the interpreter.
638
639
640.. envvar:: PYTHONMALLOCSTATS
641
642 If set, Python will print memory allocation statistics every time a new
643 object arena is created, and on shutdown.
Note: See TracBrowser for help on using the repository browser.