1. Ligne de commande et environnement¶
L’interpréteur CPython analyse la ligne de commande et l’environnement à la recherche de différents paramètres/
Le format des lignes de commandes utilisées par d’autres implémentations peut être différent. Voir Alternate Implementations pour plus d’informations.
1.1. Ligne de commande¶
Quand vous invoquez Python, vous pouvez spécifier n’importe laquelle de ces options :
python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]
Le cas d’utilisation le plus courant est, bien entendu, la simple invocation d’un script :
python myscript.py
1.1.1. Options de l’interface¶
L’interface de l’interpréteur ressemble à celle du shell UNIX, mais fournit quelques méthodes d’invocation supplémentaires :
- When called with standard input connected to a tty device, it prompts for commands and executes them until an EOF (an end-of-file character, you can produce that with Ctrl-D on UNIX or Ctrl-Z, Enter on Windows) is read.
- Quand l’interpréteur est appelé avec argument correspondant à un nom de fichier ou avec un fichier comme entrée standard, il lit et exécute le script contenu dans ce fichier.
- Quand l’interpréteur est appelé avec un argument correspondant à un répertoire, il lit et exécute un script nommé d’une certaine façon depuis ce répertoire.
- Quand l’interpréteur est appelé avec l’option
-c commande
, il exécute la ou les instructions Python données comme commande. Ici commande peut contenir plusieurs instructions séparées par des fins de ligne. Les blancs en début de ligne ne sont pas ignorés dans les instructions Python ! - Quand l’interpréteur est appelé avec l’option
-m nom-de-module
, le module donné est recherché dans le chemin des modules Python et est exécuté en tant que script.
En mode non-interactif, toute l’entrée est analysée avant d’être exécutée.
Une option d’interface termine la listes des options consommées par l’interpréteur ; tous les arguments échoueront dans sys.argv
— notez que le premier élément, à l’indice zéro (sys.argv|0]
), est une chaîne de caractères indiquant la source du programme.
-
-c
<command>
¶ Exécute le code Python dans command. command peut être une ou plusieurs instructions, séparées par des fins de ligne, dont les espaces en debut de ligne sont significatifs, comme dans le code d’un module.
Si cette option est donnée, le premier élément de
sys.argv
sera"-c"
et le répertoire courant sera ajouté au début desys.path
(permettant aux modules de ce répertoire d’être importé comme des modules de premier niveau).
-
-m
<module-name>
¶ Parcourir
sys.path
à la recherche du module donné et exécuter son contenu en tant que module__main__
.Since the argument is a module name, you must not give a file extension (
.py
). Themodule-name
should be a valid Python module name, but the implementation may not always enforce this (e.g. it may allow you to use a name that includes a hyphen).Les noms de paquets sont aussi autorisés (ainsi que les namespace packages). Quand un nom de paquet est donné à la place d’un module habituel, l’interpréteur exécutera
<pkg>.__main__
comme module principal. Ce comportement est délibérement identique à un dossier on un fichier zip donné à en argument à l’interpréteur comme script.Note
Cette option ne peut pas être utilisée avec les modules intégrés et les modules d’extension écrits en C, étant donné qu’il ne possèdent pas de fichiers modules en Python. Cependant, elle peut toujours être utilisées pour les modules pré-complilés, même si le fichier source original n’est pas disponible.
Si cette option est donnée, le premier élément de
sys.argv
sera le chemin complet d’accès au fichier du module (pendant que le fichier est recherché, le premier élément sera mis à"-m"
). Comme avec l’option-c
, le dossier courant sera ajouté au début desys.path
.De nombreux modules de la bibliothèque standard contiennent du code qui est invoqué quand ils sont exécutés comme scripts. Un exemple est le module
timeit
:python -mtimeit -s 'setup here' 'benchmarked code here' python -mtimeit -h # for details
Voir aussi
runpy.run_module()
- Equivalent functionality directly available to Python code
PEP 338 – Exécuter des modules en tant que scripts
Modifié dans la version 3.1: Supply the package name to run a
__main__
submodule.Modifié dans la version 3.4: namespace packages are also supported
-
-
Lit les commandes depuis l’entrée standard (
sys.stdin
). Si l’entrée standard est un terminal, l”-i
est activée implicitement.Si cette option est donnée, le premier élément de
sys.argv
sera"-"
et le dossier courant sera ajouté au début desys.path
.
-
<script>
Exécute le code Python contenu dans script, qui doit être un chemin d’accès au fichier (absolu ou relatif), se référant à un fichier Python, à un répertoire contenant un fichier
__main__.py
ou à un fichier zip contenant un fichier__main__.py
.Si cette option est donnée, le premier élément de
sys.argv
sera le nom du script comme donné sur la ligne de commande.Si le nom du script se réfère directement à un fichier Python, le répertoire contenant ce fichier est ajouté au début de
sys.path
, et le fichier est exécuté en tant que module__main__
.Si le nom du script fait référence à un dossier ou à un fichier zip, le nom du script est ajouté au début de
sys.path
et le fichier__main__.py
à cet endroit est exécuté en tant que module__main__
.Voir aussi
runpy.run_path()
- Equivalent functionality directly available to Python code
Si aucune option d’interface n’est donnée, -i
est implicite, sys.argv[0]
est une chaine vide (""
) et le dossier courant sera ajouté au début de sys.path
. Aussi, la complétion des tabulations et l’édition de l’historique seront automatiquement activés, s’ils sont disponnibles sur votre système (voir Readline configuration).
Voir aussi
Modifié dans la version 3.4: Automatic enabling of tab-completion and history editing.
1.1.2. Options génériques¶
1.1.3. Options diverses¶
-
-b
¶
Issue a warning when comparing
bytes
orbytearray
withstr
orbytes
withint
. Issue an error when the option is given twice (-bb
).
-
-B
¶
If given, Python won’t try to write
.pyc
or.pyo
files on the import of source modules. See alsoPYTHONDONTWRITEBYTECODE
.
-
-d
¶
Activer la sortie de l’analyseur de débogage (pour les magiciens uniquement, en fonction des options de compilation). Voir aussi
PYTHONDEBUG
.
-
-E
¶
Ignorer toutes les variables d’environnement
PYTHON*
, par exemple,PYTHONPATH
etPYTHONHOME
, qui pourraient être définies.
-
-i
¶
Quand un script est passé comme premier argument ou que l’option
-c
est utilisée, entrer en mode interactif après avoir exécuté le script ou la commande, même lorsquesys.stdin
ne semble pas être un terminal. Le fichierPYTHONSTARTUP
n’est pas lu.Cela peut être utile pour examiner les variables globales ou une trace de la pile lorsque le script lève une exception. Voir aussi
PYTHONINSPECT
.
-
-I
¶
Run Python in isolated mode. This also implies -E and -s. In isolated mode
sys.path
contains neither the script’s directory nor the user’s site-packages directory. AllPYTHON*
environment variables are ignored, too. Further restrictions may be imposed to prevent the user from injecting malicious code.Nouveau dans la version 3.4.
-
-O
¶
Turn on basic optimizations. This changes the filename extension for compiled (bytecode) files from
.pyc
to.pyo
. See alsoPYTHONOPTIMIZE
.
-
-q
¶
Don’t display the copyright and version messages even in interactive mode.
Nouveau dans la version 3.2.
-
-R
¶
Kept for compatibility. On Python 3.3 and greater, hash randomization is turned on by default.
On previous versions of Python, this option turns on hash randomization, so that the
__hash__()
values of str, bytes and datetime are « salted » with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.Hash randomization is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict construction, O(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.
PYTHONHASHSEED
allows you to set a fixed value for the hash seed secret.Nouveau dans la version 3.2.3.
-
-s
¶
Ne pas ajouter le
user site-packages directory
àsys.path
.Voir aussi
PEP 370 – Per user site-packages directory
-
-S
¶
Désactiver l’importation du module
site
et les modifications locales desys.path
qu’il implique. Désactive aussi ces manipulations sisite
est importé explicitement pluis tard (appellezsite.main()
si vous voulez les déclencher).
-
-u
¶
Désactive les buffers de la couche binaire des flux stdout and stderr (disponible comme leur attribut
buffer
). La couche d’entrée-sortie sera mise en buffer ligne par ligne lors de l’écriture sur la console, ou par blocs si elle est redirigée sur un fichier non-interactif.Voir aussi
PYTHONUNBUFFERED
.
-
-v
¶
Print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. When given twice (
-vv
), print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit. See alsoPYTHONVERBOSE
.
-
-W
arg
¶ Warning control. Python’s warning machinery by default prints warning messages to
sys.stderr
. A typical warning message has the following form:file:line: category: message
Par défaut, chaque avertissement est affiché une fois pour chaque ligne de source où il se trouve. Cette option définit à quelle fréquence afficher ces avertissements.
Multiple
-W
options may be given; 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 is printed about invalid options when the first warning is issued).Warnings can also be controlled from within a Python program using the
warnings
module.La forme la plus simple de l’argument est l’une des chaînes d’action suivante (ou une abréviation unique) :
ignore
- Ignorer tous les avertissements.
default
- Explicitly request the default behavior (printing each warning once per source line).
all
- Affiche un avertissement à chaque fois qu’il se produit (ce qui peut générer beaucoup de messages si l’avertissement est déclenché à plusieurs reprises, comme à l’intérieur d’une boucle).
module
- Affiche chaque avertissement uniquement la première fois qu’il apparaît dans chaque module.
once
- Affiche chaque avertissement uniquement la première fois qu’il apparaît dans le programme.
error
- Déclenche une exception au lieu d’afficher un message d’avertissement.
La forme complète de l’argument est :
action:message:category:module:line
Ici, action est tel qu’expliqué ci-dessus, mais s’applique uniquement aux messages qui correspondent aux champs restants. Les champs vides correspondent à toutes les valeurs ; les champs vides de fin peuvent être omis. Le champ message correspond au début du message d’avertissement affiché, cette expression est insensible à la casse. Le champ category correspond à la catégorie d’avertissement. Ce nom doit être un nom complet de classe ; La règle s’applique à tous les messages d’alertes construits avec une classe héritante de celle spécifiée. Le nom de la classe complète doit être donnée. Le champ module correspond au nom (pleinement qualifié) du module, cette correspondance est sensible à la casse. Le champ line correspond au numéro de ligne, où zéro correspond à n’importe quel numéro de ligne et correspond donc à l’option par défaut.
-
-x
¶
Skip the first line of the source, allowing use of non-Unix forms of
#!cmd
. This is intended for a DOS specific hack only.Note
Les numéros de ligne dans les messages d’erreur seront décalés de un.
-
-X
¶
Reserved for various implementation-specific options. CPython currently defines the following possible values:
-X faulthandler
to enablefaulthandler
;-X showrefcount
to enable the output of the total reference count and memory blocks (only works on debug builds);-X tracemalloc
to start tracing Python memory allocations using thetracemalloc
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. See thetracemalloc.start()
for more information.
It also allows to pass arbitrary values and retrieve them through the
sys._xoptions
dictionary.Modifié dans la version 3.2: It is now allowed to pass
-X
with CPython.Nouveau dans la version 3.3: The
-X faulthandler
option.Nouveau dans la version 3.4: The
-X showrefcount
and-X tracemalloc
options.
1.2. Variables d’environnement¶
These environment variables influence Python’s behavior, they are processed before the command-line switches other than -E or -I. It is customary that command-line switches override environmental variables where there is a conflict.
-
PYTHONHOME
¶ Change the location of the standard Python libraries. By default, the libraries are searched in
prefix/lib/pythonversion
andexec_prefix/lib/pythonversion
, whereprefix
andexec_prefix
are installation-dependent directories, both defaulting to/usr/local
.When
PYTHONHOME
is set to a single directory, its value replaces bothprefix
andexec_prefix
. To specify different values for these, setPYTHONHOME
toprefix:exec_prefix
.
-
PYTHONPATH
¶ Augment the default search path for module files. The format is the same as the shell’s
PATH
: one or more directory pathnames separated byos.pathsep
(e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.In addition to normal directories, individual
PYTHONPATH
entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.The default search path is installation dependent, but generally begins with
prefix/lib/pythonversion
(seePYTHONHOME
above). It is always appended toPYTHONPATH
.An additional directory will be inserted in the search path in front of
PYTHONPATH
as described above under Options de l’interface. The search path can be manipulated from within a Python program as the variablesys.path
.
-
PYTHONSTARTUP
¶ If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. You can also change the prompts
sys.ps1
andsys.ps2
and the hooksys.__interactivehook__
in this file.
-
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.
-
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.
-
PYTHONINSPECT
¶ If this is set to a non-empty string it is equivalent to specifying the
-i
option.This variable can also be modified by Python code using
os.environ
to force inspect mode on program termination.
-
PYTHONUNBUFFERED
¶ If this is set to a non-empty string it is equivalent to specifying the
-u
option.
-
PYTHONVERBOSE
¶ If this is set to a non-empty string it is equivalent to specifying the
-v
option. If set to an integer, it is equivalent to specifying-v
multiple times.
-
PYTHONCASEOK
¶ If this is set, Python ignores case in
import
statements. This only works on Windows and OS X.
-
PYTHONDONTWRITEBYTECODE
¶ If this is set to a non-empty string, Python won’t try to write
.pyc
or.pyo
files on the import of source modules. This is equivalent to specifying the-B
option.
-
PYTHONHASHSEED
¶ If this variable is not set or set to
random
, a random value is used to seed the hashes of str, bytes and datetime 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.
Nouveau dans la version 3.2.3.
-
PYTHONIOENCODING
¶ If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax
encodingname:errorhandler
. Both theencodingname
and the:errorhandler
parts are optional and have the same meaning as instr.encode()
.For stderr, the
:errorhandler
part is ignored; the handler will always be'backslashreplace'
.Modifié dans la version 3.4: The
encodingname
part is now optional.
-
PYTHONNOUSERSITE
¶ If this is set, Python won’t add the
user site-packages directory
tosys.path
.Voir aussi
PEP 370 – Per user site-packages directory
-
PYTHONUSERBASE
¶ Defines the
user base directory
, which is used to compute the path of theuser site-packages directory
and Distutils installation paths forpython setup.py install --user
.Voir aussi
PEP 370 – Per user site-packages directory
-
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.
-
PYTHONWARNINGS
¶ This is equivalent to the
-W
option. If set to a comma separated string, it is equivalent to specifying-W
multiple times.
-
PYTHONFAULTHANDLER
¶ If this environment variable is set to a non-empty string,
faulthandler.enable()
is called at startup: install a handler forSIGSEGV
,SIGFPE
,SIGABRT
,SIGBUS
andSIGILL
signals to dump the Python traceback. This is equivalent to-X
faulthandler
option.Nouveau dans la version 3.3.
-
PYTHONTRACEMALLOC
¶ If this environment variable is set to a non-empty string, start tracing Python memory allocations using the
tracemalloc
module. The value of the variable is the maximum number of frames stored in a traceback of a trace. For example,PYTHONTRACEMALLOC=1
stores only the most recent frame. See thetracemalloc.start()
for more information.Nouveau dans la version 3.4.
-
PYTHONASYNCIODEBUG
¶ If this environment variable is set to a non-empty string, enable the debug mode of the
asyncio
module.Nouveau dans la version 3.4.
1.2.1. Debug-mode variables¶
Setting these variables only has an effect in a debug build of Python, that is,
if Python was configured with the --with-pydebug
build option.
-
PYTHONTHREADDEBUG
¶ If set, Python will print threading debug info.
-
PYTHONDUMPREFS
¶ If set, Python will dump objects and reference counts still alive after shutting down the interpreter.
-
PYTHONMALLOCSTATS
¶ If set, Python will print memory allocation statistics every time a new object arena is created, and on shutdown.