1. コマンドラインと環境¶
CPython インタプリタはコマンドラインと環境を読み取って様々な設定を行ないます。
他の実装のコマンドラインスキームは CPython とは異なります。さらなる情報は 別のPythonの実装 を参照してください。
1.1. コマンドライン¶
Python を起動するとき、以下のうち任意のオプションを指定できます:
python [-bBdEhiIOPqRsSuvVWx?] [-c command | -m module-name | script | - ] [args]
もちろん、もっとも一般的な利用方法は、単純にスクリプトを起動することです:
python myscript.py
1.1.1. インターフェイスオプション¶
インタプリタのインターフェイスは UNIX シェルのものに似ていますが、より多くの起動方法を提供しています:
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.
ファイル名引数か、標準入力としてファイルを渡された場合、そのファイルからスクリプトを読み込んで実行します。
ディレクトリ名を引数に受け取った場合、そのディレクトリから適切な名前のスクリプトファイルを読み込んで実行します。
-c コマンドオプションを利用して起動された場合、 コマンド として渡された Python の文を実行します。 コマンド の部分には改行で区切られた複数行を指定することもできます。行の先頭の空白文字は Python 文の重要要素です!-m モジュール名として Python モジュールパスにあるモジュールを指定された場合、そのモジュールをスクリプトとして実行します。
非インタラクティブモードでは、入力の全体が実行前にパースされます。
インタプリタによって消費されるオプションリストが終了したあと、継続する全ての引数は sys.argv に渡ります。 -- ただし、添字 0 の先頭要素(sys.argv[0]) はプログラムのソース自体を示す文字列です。
- -c <command>¶
command 内の Python コードを実行します。 command は改行によって区切られた1行以上の文です。通常のモジュールのコードと同じく、行頭の空白文字は意味を持ちます。
このオプションが指定された場合、
sys.argvの最初の要素は"-c"になり、カレントディレクトリがsys.pathの先頭に追加されます (そのディレクトリにあるモジュールをトップレベルモジュールとして import 出来るようになります)。引数
commandを指定して 監査イベントcpython.run_commandを送出します。
- -m <module-name>¶
sys.pathから指定されたモジュール名のモジュールを探し、その内容を__main__モジュールとして実行します。引数は module 名なので、拡張子 (
.py) を含めてはいけません。モジュール名は有効な Python の絶対モジュール名 (absolute module name) であるべきですが、実装がそれを強制しているとは限りません (例えば、ハイフンを名前に含める事を許可するかもしれません)。パッケージ名 (名前空間パッケージも含む) でも構いません。通常のモジュールの代わりにパッケージ名が与えられた場合、インタプリタは
<pkg>.__main__を main モジュールとして実行します。この挙動はスクリプト引数として渡されたディレクトリや zip ファイルをインタプリタが処理するのと意図的に同じにしています。注釈
このオプションは組み込みモジュールや C で書かれた拡張モジュールには利用できません。 Python モジュールファイルを持っていないからです。しかし、コンパイル済みのモジュールは、たとえ元のソースファイルがなくても利用可能です。
このオプションが指定された場合、
sys.argvの最初の要素はモジュールファイルのフルパスになります (モジュールファイルを検索している間、最初の要素は"-m"に設定されます)。-cオプションと同様に、カレントディレクトリがsys.pathの先頭に追加されます。-Ioption can be used to run the script in isolated mode wheresys.pathcontains neither the current directory nor the user's site-packages directory. AllPYTHON*environment variables are ignored, too.多くの標準ライブラリモジュールにはスクリプトとして実行された時のためのコードがあります。例えば、
timeitモジュールは次のように実行可能です:python -m timeit -s "setup here" "benchmarked code here" python -m timeit -h # for details
引数
module-nameを指定して 監査イベントcpython.run_moduleを送出します。バージョン 3.1 で変更:
__main__サブモジュールを実行するパッケージ名が提供されました。バージョン 3.4 で変更: 名前空間パッケージもサポートされました
- -
標準入力 (
sys.stdin) からコマンドを読み込みます。標準入力がターミナルだった場合、暗黙的に-iオプションが指定されます。このオプションが指定された場合、
sys.argvの最初の要素は"-"で、カレントディレクトリがsys.pathの先頭に追加されます。引数無しで 監査イベント
cpython.run_stdinを送出します。
- <script>
script 内の Python コードを実行します。 script は、Python ファイル、
__main__.pyファイルがあるディレクトリ、__main__.pyファイルがある zip ファイルのいずれかの、ファイルシステム上の (絶対または相対) パスでなければなりません。このオプションが指定された場合、
sys.argvの最初の要素はコマンドラインで指定されたスクリプト名になります。スクリプト名が Python ファイルを直接指定していた場合、そのファイルを含むディレクトリが
sys.pathの先頭に追加され、そのファイルは__main__モジュールとして実行されます。スクリプト名がディレクトリか zip ファイルを指定していた場合、スクリプト名が
sys.pathに追加され、その中の__main__.pyファイルが__main__モジュールとして実行されます。-Ioption can be used to run the script in isolated mode wheresys.pathcontains neither the script's directory nor the user's site-packages directory. AllPYTHON*environment variables are ignored, too.引数
filenameを指定して 監査イベントcpython.run_fileを送出します。参考
runpy.run_path()Python コードで直接使える等価な機能
インターフェイスオプションが与えられなかった場合、-i が暗黙的に指定され、sys.argv[0] が空の文字列 ("") になり、 現在のディレクトリが sys.path の先頭に追加されます。また、利用可能であればタブ補完と履歴編集が自動的に有効化されます (readline の設定 を参照してください)。
参考
バージョン 3.4 で変更: タブ補完と履歴の編集が自動的に有効化されます。
1.1.2. 一般オプション¶
- -?¶
- -h¶
- --help¶
Print a short description of all command line options and corresponding environment variables and exit.
- --help-env¶
Print a short description of Python-specific environment variables and exit.
Added in version 3.11.
- --help-xoptions¶
Print a description of implementation-specific
-Xoptions and exit.Added in version 3.11.
- --help-all¶
Print complete usage information and exit.
Added in version 3.11.
1.1.3. その他のオプション¶
- -b¶
Issue a warning when converting
bytesorbytearraytostrwithout specifying encoding or comparingbytesorbytearraywithstrorbyteswithint. Issue an error when the option is given twice (-bb).
- -B¶
与えられた場合、Python はソースモジュールのインポート時に
.pycファイルの作成を試みません。PYTHONDONTWRITEBYTECODE環境変数も参照してください。
- --check-hash-based-pycs default|always|never¶
Control the validation behavior of hash-based
.pycfiles. See キャッシュされたバイトコードの無効化. When set todefault, checked and unchecked hash-based bytecode cache files are validated according to their default semantics. When set toalways, all hash-based.pycfiles, whether checked or unchecked, are validated against their corresponding source file. When set tonever, hash-based.pycfiles are not validated against their corresponding source files.The semantics of timestamp-based
.pycfiles are unaffected by this option.
- -d¶
Turn on parser debugging output (for expert only). See also the
PYTHONDEBUGenvironment variable.This option requires a debug build of Python, otherwise it's ignored.
- -E¶
Ignore all
PYTHON*environment variables, e.g.PYTHONPATHandPYTHONHOME, that might be set.
- -i¶
Enter interactive mode after execution.
Using the
-ioption will enter interactive mode in any of the following circumstances:Interactive mode will start even when
sys.stdindoes not appear to be a terminal. ThePYTHONSTARTUPfile is not read.このオプションはグローバル変数や、スクリプトが例外を発生させるときにそのスタックトレースを調べるのに便利です。
PYTHONINSPECTも参照してください。
- -I¶
Python を隔離モードで実行します。
-E、-P、および-sオプションも暗黙的に指定されます。In isolated mode
sys.pathcontains 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.Added in version 3.4.
- -O¶
Remove assert statements and any code conditional on the value of
__debug__. Augment the filename for compiled (bytecode) files by adding.opt-1before the.pycextension (see PEP 488). See alsoPYTHONOPTIMIZE.バージョン 3.5 で変更: PEP 488 に従って
.pycファイル名を変更します。
- -OO¶
Do
-Oand also discard docstrings. Augment the filename for compiled (bytecode) files by adding.opt-2before the.pycextension (see PEP 488).バージョン 3.5 で変更: PEP 488 に従って
.pycファイル名を変更します。
- -P¶
Don't prepend a potentially unsafe path to
sys.path:python -m modulecommand line: Don't prepend the current working directory.python script.pycommand line: Don't prepend the script's directory. If it's a symbolic link, resolve symbolic links.python -c codeandpython(REPL) command lines: Don't prepend an empty string, which means the current working directory.
See also the
PYTHONSAFEPATHenvironment variable, and-Eand-I(isolated) options.Added in version 3.11.
- -q¶
インタラクティブモードでも copyright とバージョンのメッセージを表示しません。
Added in version 3.2.
- -R¶
Turn on hash randomization. This option only has an effect if the
PYTHONHASHSEEDenvironment variable is set to0, since hash randomization is enabled by default.On previous versions of Python, this option turns on hash randomization, so that the
__hash__()values of str and bytes objects 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(n2) complexity. See http://ocert.org/advisories/ocert-2011-003.html for details.
PYTHONHASHSEEDによってハッシュシードの固定値を秘密にすることが出来ます。Added in version 3.2.3.
バージョン 3.7 で変更: このオプションが無視されなくなりました.
- -s¶
ユーザのサイトパッケージのディレクトリをsys.pathに追加しません。See also
PYTHONNOUSERSITE.参考
PEP 370 -- ユーザごとの
site-packagesディレクトリ
- -S¶
siteモジュールの import と、そのモジュールが行なっていた site ごとのsys.pathへの操作を無効にします。後でsiteを明示的に import しても、これらの操作は実行されません (実行したい場合は、site.main()を呼び出してください)。
- -u¶
Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream.
PYTHONUNBUFFEREDも参照してください。バージョン 3.7 で変更: The text layer of the stdout and stderr streams now is unbuffered.
- -v¶
モジュールが初期化されるたびにメッセージを出力し、それがどこ (ファイル名やビルトインモジュール) からロードされたのかを表示します。 二回与えられた場合 (
-vv) は、モジュールを検索するときにチェックしたファイルごとにメッセージを出力します。また、終了時のモジュールクリーンアップに関する情報も提供します。バージョン 3.10 で変更: The
sitemodule reports the site-specific paths and.pthfiles being processed.PYTHONVERBOSEも参照してください。
- -W arg¶
警告制御。 Python の警告機構はデフォルトでは警告メッセージを
sys.stderrに表示します。The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default):
-Wdefault # Warn once per call location -Werror # Convert to exceptions -Walways # Warn every time -Wall # Same as -Walways -Wmodule # Warn once per calling module -Wonce # Warn once per Python process -Wignore # Never warn
The action names can be abbreviated as desired and the interpreter will resolve them to the appropriate action name. For example,
-Wiis the same as-Wignore.引数の完全形は次のようになります:
action:message:category:module:lineno
Empty fields match all values; trailing empty fields may be omitted. For example
-W ignore::DeprecationWarningignores all DeprecationWarning warnings.The action field is as explained above but only applies to warnings that match the remaining fields.
The message field must match the whole warning message; this match is case-insensitive.
The category field matches the warning category (ex:
DeprecationWarning). This must be a class name; the match test whether the actual warning category of the message is a subclass of the specified warning category.The module field matches the (fully qualified) module name; this match is case-sensitive.
The lineno field matches the line number, where zero matches all line numbers and is thus equivalent to an omitted line number.
複数の
-Wオプションを指定することができます。警告が1つ以上のオプションとマッチしたときは、最後にマッチしたオプションのアクションが有効になります。不正な-Wオプションは無視されます (最初の警告が発生したときに、不正なオプションに対する警告メッセージが表示されます)。Warnings can also be controlled using the
PYTHONWARNINGSenvironment variable and from within a Python program using thewarningsmodule. For example, thewarnings.filterwarnings()function can be used to use a regular expression on the warning message.詳しくは 警告フィルタ と Describing Warning Filters を参照してください。
- -x¶
Unix 以外の形式の
#!cmdを使うために、ソースの最初の行をスキップします。これは、DOS専用のハックのみを目的としています。
- -X¶
様々な実装固有のオプションのために予約されています。現在のところ CPython は以下の値を定義しています:
-X faulthandlerto enablefaulthandler. See alsoPYTHONFAULTHANDLER.Added in version 3.3.
-X showrefcountto output the total reference count and number of used memory blocks when the program finishes or after each statement in the interactive interpreter. This only works on debug builds.Added in version 3.4.
-X tracemallocto start tracing Python memory allocations using thetracemallocmodule. By default, only the most recent frame is stored in a traceback of a trace. Use-X tracemalloc=NFRAMEto start tracing with a traceback limit of NFRAME frames. Seetracemalloc.start()andPYTHONTRACEMALLOCfor more information.Added in version 3.4.
-X int_max_str_digitsconfigures the integer string conversion length limitation. See alsoPYTHONINTMAXSTRDIGITS.Added in version 3.11.
-X importtimeto show how long each import takes. It shows module name, cumulative time (including nested imports) and self time (excluding nested imports). Note that its output may be broken in multi-threaded application. Typical usage ispython3 -X importtime -c 'import asyncio'. See alsoPYTHONPROFILEIMPORTTIME.Added in version 3.7.
-X dev: enable Python Development Mode, introducing additional runtime checks that are too expensive to be enabled by default. See alsoPYTHONDEVMODE.Added in version 3.7.
-X utf8enables the Python UTF-8 Mode.-X utf8=0explicitly disables Python UTF-8 Mode (even when it would otherwise activate automatically). See alsoPYTHONUTF8.Added in version 3.7.
-X pycache_prefix=PATHenables writing.pycfiles to a parallel tree rooted at the given directory instead of to the code tree. See alsoPYTHONPYCACHEPREFIX.Added in version 3.8.
-X warn_default_encodingissues aEncodingWarningwhen the locale-specific default encoding is used for opening files. See alsoPYTHONWARNDEFAULTENCODING.Added in version 3.10.
-X no_debug_rangesdisables the inclusion of the tables mapping extra location information (end line, start column offset and end column offset) to every instruction in code objects. This is useful when smaller code objects and pyc files are desired as well as suppressing the extra visual location indicators when the interpreter displays tracebacks. See alsoPYTHONNODEBUGRANGES.Added in version 3.11.
-X frozen_modulesdetermines whether or not frozen modules are ignored by the import machinery. A value of "on" means they get imported and "off" means they are ignored. The default is "on" if this is an installed Python (the normal case). If it's under development (running from the source tree) then the default is "off". Note that the "importlib_bootstrap" and "importlib_bootstrap_external" frozen modules are always used, even if this flag is set to "off".Added in version 3.11.
-X perfenables support for the Linuxperfprofiler. When this option is provided, theperfprofiler will be able to report Python calls. This option is only available on some platforms and will do nothing if is not supported on the current system. The default value is "off". See alsoPYTHONPERFSUPPORTand Python support for the Linux perf profiler.Added in version 3.12.
任意の値を渡し、
sys._xoptions辞書から取り出すことも出来ます。Added in version 3.2.
バージョン 3.9 で変更: Removed the
-X showalloccountoption.バージョン 3.10 で変更: Removed the
-X oldparseroption.
1.1.4. Options you shouldn't use¶
1.2. 環境変数¶
以下の環境変数は Python の挙動に影響します。環境変数は -E や -I 以外のコマンドラインスイッチの前に処理されます。衝突したときにコマンドラインスイッチが環境変数をオーバーライドするのは慣例です。
- PYTHONHOME¶
標準 Python ライブラリの場所を変更します。デフォルトでは、ライブラリは
prefix/lib/pythonversionとexec_prefix/lib/pythonversionから検索されます。ここで、prefixとexec_prefixはインストール依存のディレクトリで、両方共デフォルトでは/usr/localです。PYTHONHOMEが1つのディレクトリに設定されている場合、その値はprefixとexec_prefixの両方を置き換えます。それらに別々の値を指定したい場合は、PYTHONHOMEをprefix:exec_prefixのように指定します。
- PYTHONPATH¶
モジュールファイルのデフォルトの検索パスを追加します。この環境変数のフォーマットはシェルの
PATHと同じで、os.pathsep(Unix ならコロン、 Windows ならセミコロン) で区切られた1つ以上のディレクトリパスです。存在しないディレクトリは警告なしに無視されます。通常のディレクトリに加えて、
PYTHONPATHのエントリはピュアPython モジュール(ソース形式でもコンパイルされた形式でも) を含む zip ファイルを参照することもできます。拡張モジュールは zip ファイルの中から import することはできません。デフォルトの検索パスはインストール依存ですが、通常は
prefix/lib/pythonversionで始まります。 (上のPYTHONHOMEを参照してください。) これは 常にPYTHONPATHに追加されます。上の インターフェイスオプション で説明されているように、追加の検索パスディレクトリが
PYTHONPATHの手前に追加されます。検索パスは Python プログラムからsys.path変数として操作することができます。
- PYTHONSAFEPATH¶
If this is set to a non-empty string, don't prepend a potentially unsafe path to
sys.path: see the-Poption for details.Added in version 3.11.
- PYTHONPLATLIBDIR¶
If this is set to a non-empty string, it overrides the
sys.platlibdirvalue.Added in version 3.9.
- PYTHONSTARTUP¶
この変数が読み込み可能なファイル名の場合、対話モードで最初のプロンプトが表示される前にそのファイルの Python コマンドが実行されます。 ファイル内で定義されているオブジェクトやインポートされたオブジェクトを対話セッションで修飾せずに使用するために、ファイルは対話的なコマンドと同じ名前空間で実行されます。 このファイルの中で、プロンプト
sys.ps1やsys.ps2、ならびにフックsys.__interactivehook__も変更できます。Raises an auditing event
cpython.run_startupwith the filename as the argument when called on startup.
- PYTHONBREAKPOINT¶
If this is set, it names a callable using dotted-path notation. The module containing the callable will be imported and then the callable will be run by the default implementation of
sys.breakpointhook()which itself is called by built-inbreakpoint(). If not set, or set to the empty string, it is equivalent to the value "pdb.set_trace". Setting this to the string "0" causes the default implementation ofsys.breakpointhook()to do nothing but return immediately.Added in version 3.7.
- PYTHONDEBUG¶
この変数に空でない文字列を設定するのは
-dオプションを指定するのと等価です。整数を指定した場合、-dを複数回指定したのと同じになります。This environment variable requires a debug build of Python, otherwise it's ignored.
- PYTHONINSPECT¶
この変数に空でない文字列を設定するのは
-iオプションを指定するのと等価です。この変数は Python コードから
os.environを使って変更して、プログラム終了時のインスペクトモードを強制することができます。引数無しで 監査イベント
cpython.run_stdinを送出します。バージョン 3.12.5 で変更: (also 3.11.10, 3.10.15, 3.9.20, and 3.8.20) Emits audit events.
- PYTHONDONTWRITEBYTECODE¶
この変数に空でない文字列を設定した場合、 Python はソースモジュールのインポート時に
.pycファイルを作成しようとはしなくなります。-Bオプションを指定するのと等価です。
- PYTHONPYCACHEPREFIX¶
If this is set, Python will write
.pycfiles in a mirror directory tree at this path, instead of in__pycache__directories within the source tree. This is equivalent to specifying the-Xpycache_prefix=PATHoption.Added in version 3.8.
- PYTHONHASHSEED¶
この変数が設定されていない場合や
randomに設定された場合、乱数値が str、bytes オブジェクトのハッシュのシードに使われます。PYTHONHASHSEEDが整数値に設定された場合、その値はハッシュランダム化が扱う型の hash() 生成の固定シードに使われます。その目的は再現性のあるハッシュを可能にすることです。例えばインタープリタ自身の自己テストや Python プロセスのクラスタでハッシュ値を共有するのに用います。
整数は [0,4294967295] の十進数でなければなりません。0 を指定するとハッシュランダム化は無効化されます。
Added in version 3.2.3.
- PYTHONINTMAXSTRDIGITS¶
If this variable is set to an integer, it is used to configure the interpreter's global integer string conversion length limitation.
Added in version 3.11.
- PYTHONIOENCODING¶
この変数がインタープリタ実行前に設定されていた場合、
encodingname:errorhandlerという文法で標準入力/標準出力/標準エラー出力のエンコードを上書きします。encodingnameと:errorhandlerの部分はどちらも任意で、str.encode()と同じ意味を持ちます。標準エラー出力の場合、
:errorhandlerの部分は無視されます; ハンドラは常に'backslashreplace'です。バージョン 3.4 で変更:
encodingnameの部分が任意になりました。バージョン 3.6 で変更: On Windows, the encoding specified by this variable is ignored for interactive console buffers unless
PYTHONLEGACYWINDOWSSTDIOis also specified. Files and pipes redirected through the standard streams are not affected.
- PYTHONNOUSERSITE¶
この環境変数が設定されている場合、 Python は
ユーザ site-packages ディレクトリをsys.pathに追加しません。参考
PEP 370 -- ユーザごとの
site-packagesディレクトリ
- PYTHONUSERBASE¶
Defines the
user base directory, which is used to compute the path of theuser site-packages directoryand installation paths forpython -m pip install --user.参考
PEP 370 -- ユーザごとの
site-packagesディレクトリ
- PYTHONEXECUTABLE¶
この環境変数が設定された場合、
sys.argv[0]に、C ランタイムから取得した値の代わりにこの環境変数の値が設定されます。macOS でのみ動作します。
- PYTHONWARNINGS¶
This is equivalent to the
-Woption. If set to a comma separated string, it is equivalent to specifying-Wmultiple times, with filters later in the list taking precedence over those earlier in the list.The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default):
PYTHONWARNINGS=default # Warn once per call location PYTHONWARNINGS=error # Convert to exceptions PYTHONWARNINGS=always # Warn every time PYTHONWARNINGS=all # Same as PYTHONWARNINGS=always PYTHONWARNINGS=module # Warn once per calling module PYTHONWARNINGS=once # Warn once per Python process PYTHONWARNINGS=ignore # Never warn
詳しくは 警告フィルタ と Describing Warning Filters を参照してください。
- PYTHONFAULTHANDLER¶
If this environment variable is set to a non-empty string,
faulthandler.enable()is called at startup: install a handler forSIGSEGV,SIGFPE,SIGABRT,SIGBUSandSIGILLsignals to dump the Python traceback. This is equivalent to-Xfaulthandleroption.Added in version 3.3.
- PYTHONTRACEMALLOC¶
If this environment variable is set to a non-empty string, start tracing Python memory allocations using the
tracemallocmodule. The value of the variable is the maximum number of frames stored in a traceback of a trace. For example,PYTHONTRACEMALLOC=1stores only the most recent frame. See thetracemalloc.start()function for more information. This is equivalent to setting the-Xtracemallocoption.Added in version 3.4.
- PYTHONPROFILEIMPORTTIME¶
If this environment variable is set to a non-empty string, Python will show how long each import takes. This is equivalent to setting the
-Ximporttimeoption.Added in version 3.7.
- PYTHONMALLOC¶
Set the Python memory allocators and/or install debug hooks.
Set the family of memory allocators used by Python:
default: use the default memory allocators.malloc: use themalloc()function of the C library for all domains (PYMEM_DOMAIN_RAW,PYMEM_DOMAIN_MEM,PYMEM_DOMAIN_OBJ).pymalloc: use the pymalloc allocator forPYMEM_DOMAIN_MEMandPYMEM_DOMAIN_OBJdomains and use themalloc()function for thePYMEM_DOMAIN_RAWdomain.
Install debug hooks:
debug: install debug hooks on top of the default memory allocators.malloc_debug: same asmallocbut also install debug hooks.pymalloc_debug: same aspymallocbut also install debug hooks.
Added in version 3.6.
バージョン 3.7 で変更: Added the
"default"allocator.
- PYTHONMALLOCSTATS¶
空でない文字列に設定されると、Python は新たなオブジェクトアリーナが生成される時と、シャットダウン時に pymalloc メモリアロケータ の統計情報を表示します。
This variable is ignored if the
PYTHONMALLOCenvironment variable is used to force themalloc()allocator of the C library, or if Python is configured withoutpymallocsupport.バージョン 3.6 で変更: This variable can now also be used on Python compiled in release mode. It now has no effect if set to an empty string.
- PYTHONLEGACYWINDOWSFSENCODING¶
If set to a non-empty string, the default filesystem encoding and error handler mode will revert to their pre-3.6 values of 'mbcs' and 'replace', respectively. Otherwise, the new defaults 'utf-8' and 'surrogatepass' are used.
This may also be enabled at runtime with
sys._enablelegacywindowsfsencoding().Availability: Windows.
Added in version 3.6: より詳しくは PEP 529 を参照してください。
- PYTHONLEGACYWINDOWSSTDIO¶
If set to a non-empty string, does not use the new console reader and writer. This means that Unicode characters will be encoded according to the active console code page, rather than using utf-8.
This variable is ignored if the standard streams are redirected (to files or pipes) rather than referring to console buffers.
Availability: Windows.
Added in version 3.6.
- PYTHONCOERCECLOCALE¶
If set to the value
0, causes the main Python command line application to skip coercing the legacy ASCII-based C and POSIX locales to a more capable UTF-8 based alternative.If this variable is not set (or is set to a value other than
0), theLC_ALLlocale override environment variable is also not set, and the current locale reported for theLC_CTYPEcategory is either the defaultClocale, or else the explicitly ASCII-basedPOSIXlocale, then the Python CLI will attempt to configure the following locales for theLC_CTYPEcategory in the order listed before loading the interpreter runtime:C.UTF-8C.utf8UTF-8
If setting one of these locale categories succeeds, then the
LC_CTYPEenvironment variable will also be set accordingly in the current process environment before the Python runtime is initialized. This ensures that in addition to being seen by both the interpreter itself and other locale-aware components running in the same process (such as the GNUreadlinelibrary), the updated setting is also seen in subprocesses (regardless of whether or not those processes are running a Python interpreter), as well as in operations that query the environment rather than the current C locale (such as Python's ownlocale.getdefaultlocale()).Configuring one of these locales (either explicitly or via the above implicit locale coercion) automatically enables the
surrogateescapeerror handler forsys.stdinandsys.stdout(sys.stderrcontinues to usebackslashreplaceas it does in any other locale). This stream handling behavior can be overridden usingPYTHONIOENCODINGas usual.For debugging purposes, setting
PYTHONCOERCECLOCALE=warnwill cause Python to emit warning messages onstderrif either the locale coercion activates, or else if a locale that would have triggered coercion is still active when the Python runtime is initialized.Also note that even when locale coercion is disabled, or when it fails to find a suitable target locale,
PYTHONUTF8will still activate by default in legacy ASCII-based locales. Both features must be disabled in order to force the interpreter to useASCIIinstead ofUTF-8for system interfaces.Availability: Unix.
Added in version 3.7: より詳しくは PEP 538 を参照をしてください。
- PYTHONDEVMODE¶
If this environment variable is set to a non-empty string, enable Python Development Mode, introducing additional runtime checks that are too expensive to be enabled by default. This is equivalent to setting the
-Xdevoption.Added in version 3.7.
- PYTHONUTF8¶
If set to
1, enable the Python UTF-8 Mode.If set to
0, disable the Python UTF-8 Mode.Setting any other non-empty string causes an error during interpreter initialisation.
Added in version 3.7.
- PYTHONWARNDEFAULTENCODING¶
If this environment variable is set to a non-empty string, issue a
EncodingWarningwhen the locale-specific default encoding is used.詳細は Opt-in EncodingWarning を参照してください。
Added in version 3.10.
- PYTHONNODEBUGRANGES¶
If this variable is set, it disables the inclusion of the tables mapping extra location information (end line, start column offset and end column offset) to every instruction in code objects. This is useful when smaller code objects and pyc files are desired as well as suppressing the extra visual location indicators when the interpreter displays tracebacks.
Added in version 3.11.
- PYTHONPERFSUPPORT¶
If this variable is set to a nonzero value, it enables support for the Linux
perfprofiler so Python calls can be detected by it.If set to
0, disable Linuxperfprofiler support.See also the
-X perfcommand-line option and Python support for the Linux perf profiler.Added in version 3.12.
1.2.1. デバッグモード変数¶
- PYTHONDUMPREFS¶
設定された場合、 Python はインタプリタのシャットダウン後に残っているオブジェクトと参照カウントをダンプします。
Need Python configured with the
--with-trace-refsbuild option.
- PYTHONDUMPREFSFILE=FILENAME¶
If set, Python will dump objects and reference counts still alive after shutting down the interpreter into a file called FILENAME.
Need Python configured with the
--with-trace-refsbuild option.Added in version 3.11.