sys --- システムパラメータと関数


このモジュールでは、インタプリタで使用・管理している変数や、インタプリタの動作に深く関連する関数を定義しています。このモジュールは常に利用可能です。

sys.abiflags

Python が標準的な configure でビルトされた POSIX システムにおいて、PEP 3149 に記述された ABI フラグを含みます。

バージョン 3.2 で追加.

バージョン 3.8 で変更: デフォルトのフラグは空文字列になりました。 (pymalloc のための m フラグが取り除かれました)

sys.addaudithook(hook)

呼び出し可能な hook を現在の(サブ)インタープリタのアクティブな監査用フックのリストに加えます。

When an auditing event is raised through the sys.audit() function, each hook will be called in the order it was added with the event name and the tuple of arguments. Native hooks added by PySys_AddAuditHook() are called first, followed by hooks added in the current (sub)interpreter. Hooks can then log the event, raise an exception to abort the operation, or terminate the process entirely.

Note that audit hooks are primarily for collecting information about internal or otherwise unobservable actions, whether by Python or libraries written in Python. They are not suitable for implementing a "sandbox". In particular, malicious code can trivially disable or bypass hooks added using this function. At a minimum, any security-sensitive hooks must be added using the C API PySys_AddAuditHook() before initialising the runtime, and any modules allowing arbitrary memory modification (such as ctypes) should be completely removed or closely monitored.

引数無しで 監査イベント sys.addaudithook を送出します。

See the audit events table for all events raised by CPython, and PEP 578 for the original design discussion.

バージョン 3.8 で追加.

バージョン 3.8.1 で変更: RuntimeError ではない Exception は抑制されなくなりました。

CPython 実装の詳細: When tracing is enabled (see settrace()), Python hooks are only traced if the callable has a __cantrace__ member that is set to a true value. Otherwise, trace functions will skip the hook.

sys.argv

Pythonスクリプトに渡されたコマンドライン引数のリスト。 argv[0] はスクリプトの名前となりますが、フルパス名かどうかは、OSによって異なります。コマンドライン引数に -c を付けて Pythonを起動した場合、 argv[0] は文字列 '-c' となります。スクリプト名なしでPythonを起動した場合、 argv[0] は空文字列になります。

標準入力もしくはコマンドライン引数で指定されたファイルのリストに渡ってループするには、 fileinput モジュールを参照してください。

See also sys.orig_argv.

注釈

Unix では、コマンドライン引数は OS からバイト列で渡されます。 Python はそれをファイルシステムエンコーディングと "surrogateescape" エラーハンドラを使ってデコードします。 オリジナルのバイト列が必要なときには、 [os.fsencode(arg) for arg in sys.argv] で取得できます。

sys.audit(event, *args)

Raise an auditing event and trigger any active auditing hooks. event is a string identifying the event, and args may contain optional arguments with more information about the event. The number and types of arguments for a given event are considered a public and stable API and should not be modified between releases.

For example, one auditing event is named os.chdir. This event has one argument called path that will contain the requested new working directory.

sys.audit() will call the existing auditing hooks, passing the event name and arguments, and will re-raise the first exception from any hook. In general, if an exception is raised, it should not be handled and the process should be terminated as quickly as possible. This allows hook implementations to decide how to respond to particular events: they can merely log the event or abort the operation by raising an exception.

Hooks are added using the sys.addaudithook() or PySys_AddAuditHook() functions.

The native equivalent of this function is PySys_Audit(). Using the native function is preferred when possible.

See the audit events table for all events raised by CPython.

バージョン 3.8 で追加.

sys.base_exec_prefix

Python の起動中、site.py が実行される前、exec_prefix と同じ値が設定されます。仮想環境 で実行されたのでなければ、この値は変化しません; site.py が仮想環境で使用されていると判断した場合、prefix および exec_prefix は仮想環境を示すよう変更され、base_prefix および base_exec_prefix は引き続き (仮想環境が作成された) ベースの Python インストール先を示します。

バージョン 3.3 で追加.

sys.base_prefix

Python の起動中、site.py が実行される前、prefix と同じ値が設定されます。仮想環境 で実行されたのでなければ、この値は変化しません; site.py が仮想環境で使用されていると検出した場合、prefix および exec_prefix は仮想環境を示すよう変更され、base_prefix および base_exec_prefix は引き続き (仮想環境が作成された) ベースの Python インストール先を示します。

バージョン 3.3 で追加.

sys.byteorder

プラットフォームのバイト順を示します。ビッグエンディアン (最上位バイトが先頭) のプラットフォームでは 'big', リトルエンディアン (最下位バイトが先頭) では 'little' となります。

sys.builtin_module_names

コンパイル時にPythonインタプリタに組み込まれた、全てのモジュール名を含む文字列のタプル(この情報は、他の手段では取得することができません。 modules.keys() は、インポートされたモジュールのみのリストを返します。)

See also the sys.stdlib_module_names list.

sys.call_tracing(func, args)

Call func(*args), while tracing is enabled. The tracing state is saved, and restored afterwards. This is intended to be called from a debugger from a checkpoint, to recursively debug or profile some other code.

Tracing is suspended while calling a tracing function set by settrace() or setprofile() to avoid infinite recursion. call_tracing() enables explicit recursion of the tracing function.

sys.copyright

Python インタプリタの著作権を表示する文字列です。

sys._clear_type_cache()

内部の型キャッシュをクリアします。型キャッシュは属性とメソッドの検索を高速化するために利用されます。この関数は、参照リークをデバッグするときに不要な参照を削除するため だけ に利用してください。

この関数は、内部的かつ特殊な目的にのみ利用されるべきです。

sys._current_frames()

各スレッドの識別子を関数が呼ばれた時点のそのスレッドでアクティブになっている一番上のスタックフレームに結びつける辞書を返します。モジュール traceback の関数を使えばそのように与えられたフレームのコールスタックを構築できます。

この関数はデッドロックをデバッグするのに非常に有効です。デッドロック状態のスレッドの協調動作を必要としませんし、そういったスレッドのコールスタックはデッドロックである限りフリーズしたままです。デッドロックにないスレッドのフレームについては、そのフレームを調べるコードを呼んだ時にはそのスレッドの現在の実行状況とは関係ないところを指し示しているかもしれません。

この関数は、内部的かつ特殊な目的にのみ利用されるべきです。

引数無しで 監査イベント sys._current_frames を送出します。

sys._current_exceptions()

Return a dictionary mapping each thread's identifier to the topmost exception currently active in that thread at the time the function is called. If a thread is not currently handling an exception, it is not included in the result dictionary.

This is most useful for statistical profiling.

この関数は、内部的かつ特殊な目的にのみ利用されるべきです。

引数無しで 監査イベント sys._current_exceptions を送出します。

バージョン 3.12 で変更: Each value in the dictionary is now a single exception instance, rather than a 3-tuple as returned from sys.exc_info().

sys.breakpointhook()

このフック関数は組み込みの breakpoint() から呼ばれます。 デフォルトでは、この関数は pdb デバッガに処理を移行させますが、他の関数を設定することもでき、使用するデバッガを選べます。

この関数のシグネチャは何を呼び出すかに依存します。 例えば、(pdb.set_trace() などの) デフォルトの結び付けでは引数は求められませんが、追加の引数 (位置引数およびキーワード引数) を求める関数に結び付けるかもしれません。 組み込みの breakpoint() 関数は、自身の *args**kws をそのまま渡します。 breakpointhooks() の返り値が何であれ、そのまま breakpoint() から返されます。

デフォルトの実装では、最初に環境変数 PYTHONBREAKPOINT を調べます。 それが "0" に設定されていた場合は、この関数はすぐに終了します。つまり何もしません。 この環境変数が設定されていないか、空文字列に設定されていた場合は、 pdb.set_trace() が呼ばれます。 それ以外の場合は、この変数は実行する関数の名前である必要があります。関数名の指定では、例えば package.subpackage.module.function のようなドットでつながれた Python のインポートの命名体系を使ったを使います。 この場合では、 package.subpackage.module がインポートされ、そのインポートされたモジュールには function() という呼び出し可能オブジェクトがなくてはなりません。 この関数が渡された *args**kws で実行され、 function() の返り値が何であれ sys.breakpointhook() は組み込みの breakpoint() 関数にその値をそのまま返します。

PYTHONBREAKPOINT で指名された呼び出し可能オブジェクトのインポートで何かしら問題が起きた場合、 RuntimeWarning が報告されブレークポイントは無視されることに注意してください。

また、 sys.breakpointhook() がプログラム上で上書きされていた場合は PYTHONBREAKPOINT調べられない ことにも注意してください。

バージョン 3.7 で追加.

sys._debugmallocstats()

CPython のメモリアロケータの状態に関する低レベルの情報を標準エラー出力に出力します。

If Python is built in debug mode (configure --with-pydebug option), it also performs some expensive internal consistency checks.

バージョン 3.3 で追加.

CPython 実装の詳細: この関数は CPython 固有です。正確な出力形式は定義されていませんし、変更されるかもしれません。

sys.dllhandle

Python DLLのハンドルを示す整数です。

利用可能な環境: Windows 。

sys.displayhook(value)

valueNone 以外の時、repr(value)sys.stdout に出力し、builtins._ に保存します。repr(value) がエラーハンドラを sys.stdout.errors (おそらく 'strict') として sys.stdout.encoding にエンコードできない場合、エラーハンドラを 'backslashreplace' として sys.stdout.encoding にエンコードします。

sys.displayhook は、Pythonの対話セッションで入力された が評価されたときに呼び出されます。対話セッションの出力をカスタマイズする場合、 sys.displayhook に引数の数が一つの関数を指定します。

擬似コード:

def displayhook(value):
    if value is None:
        return
    # Set '_' to None to avoid recursion
    builtins._ = None
    text = repr(value)
    try:
        sys.stdout.write(text)
    except UnicodeEncodeError:
        bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
        if hasattr(sys.stdout, 'buffer'):
            sys.stdout.buffer.write(bytes)
        else:
            text = bytes.decode(sys.stdout.encoding, 'strict')
            sys.stdout.write(text)
    sys.stdout.write("\n")
    builtins._ = value

バージョン 3.2 で変更: UnicodeEncodeError には 'backslashreplace' エラーハンドラを指定してください。

sys.dont_write_bytecode

この値が真の時、Python はソースモジュールをインポートする時に .pyc ファイルを生成しません。この値は -B コマンドラインオプションと PYTHONDONTWRITEBYTECODE 環境変数の値によって、起動時に TrueFalse に設定されますが、実行時にこの変数を変更してバイトコード生成を制御することもできます。

sys._emscripten_info

A named tuple holding information about the environment on the wasm32-emscripten platform. The named tuple is provisional and may change in the future.

_emscripten_info.emscripten_version

Emscripten version as tuple of ints (major, minor, micro), e.g. (3, 1, 8).

_emscripten_info.runtime

Runtime string, e.g. browser user agent, 'Node.js v14.18.2', or 'UNKNOWN'.

_emscripten_info.pthreads

True if Python is compiled with Emscripten pthreads support.

_emscripten_info.shared_memory

True if Python is compiled with shared memory support.

Availability: Emscripten.

バージョン 3.11 で追加.

sys.pycache_prefix

If this is set (not None), Python will write bytecode-cache .pyc files to (and read them from) a parallel directory tree rooted at this directory, rather than from __pycache__ directories in the source code tree. Any __pycache__ directories in the source code tree will be ignored and new .pyc files written within the pycache prefix. Thus if you use compileall as a pre-build step, you must ensure you run it with the same pycache prefix (if any) that you will use at runtime.

A relative path is interpreted relative to the current working directory.

This value is initially set based on the value of the -X pycache_prefix=PATH command-line option or the PYTHONPYCACHEPREFIX environment variable (command-line takes precedence). If neither are set, it is None.

バージョン 3.8 で追加.

sys.excepthook(type, value, traceback)

指定したトレースバックと例外を sys.stderr に出力します。

When an exception other than SystemExit is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.

引数 hook, type, value, traceback を指定して 監査イベント sys.excepthook を送出します。

参考

The sys.unraisablehook() function handles unraisable exceptions and the threading.excepthook() function handles exception raised by threading.Thread.run().

sys.__breakpointhook__
sys.__displayhook__
sys.__excepthook__
sys.__unraisablehook__

これらのオブジェクトはそれぞれ、プログラム起動時の breakpointhook, displayhook, excepthook, unraisablehook の値を保存しています。 この値は、 breakpointhook, displayhook, excepthook, unraisablehook に不正なオブジェクトや別のオブジェクトが指定された場合に、元の値に復旧するために使用します。

バージョン 3.7 で追加: __breakpointhook__

バージョン 3.8 で追加: __unraisablehook__

sys.exception()

This function, when called while an exception handler is executing (such as an except or except* clause), returns the exception instance that was caught by this handler. When exception handlers are nested within one another, only the exception handled by the innermost handler is accessible.

If no exception handler is executing, this function returns None.

バージョン 3.11 で追加.

sys.exc_info()

This function returns the old-style representation of the handled exception. If an exception e is currently handled (so exception() would return e), exc_info() returns the tuple (type(e), e, e.__traceback__). That is, a tuple containing the type of the exception (a subclass of BaseException), the exception itself, and a traceback object which typically encapsulates the call stack at the point where the exception last occurred.

If no exception is being handled anywhere on the stack, this function return a tuple containing three None values.

バージョン 3.11 で変更: The type and traceback fields are now derived from the value (the exception instance), so when an exception is modified while it is being handled, the changes are reflected in the results of subsequent calls to exc_info().

sys.exec_prefix

Python のプラットフォーム依存なファイルがインストールされているディレクトリ名を示す文字列です。この値はサイト固有であり、デフォルトは '/usr/local' ですが、ビルド時に configure--exec-prefix 引数で指定することができます。すべての設定ファイル (pyconfig.h など) は exec_prefix/lib/pythonX.Y/config に、共有ライブラリは exec_prefix/lib/pythonX.Y/lib-dynload にインストールされます (X.Y3.2 のような Python のバージョン番号)。

注釈

仮想環境 で起動されている場合、この値は site.py によって仮想環境を示すよう変更されます。実際の Python のインストール先は base_exec_prefix から取得できます。

sys.executable

Python インタプリタの実行ファイルの絶対パスを示す文字列です。このような名前が意味を持つシステムで利用可能です。Python が自身の実行ファイルの実際のパスを取得できない場合、sys.executable は空の文字列または None になります。

sys.exit([arg])

Raise a SystemExit exception, signaling an intention to exit the interpreter.

オプション引数 arg には、終了ステータスとして整数 (デフォルトは0)や他の型のオブジェクトを指定することができます。整数を指定した場合、シェル等は 0 は "正常終了"、0 以外の整数を "異常終了" として扱います。多くのシステムでは、有効な終了ステータスは 0--127 で、これ以外の値を返した場合の動作は未定義です。システムによっては特定の終了コードに個別の意味を持たせている場合がありますが、このような定義は僅かしかありません。Unix プログラムでは構文エラーの場合には 2 を、それ以外のエラーならば 1 を返します。argNone を指定した場合は、数値の 0 を指定した場合と同じです。それ以外の型のオブジェクトを指定すると、そのオブジェクトが stderr に出力され、終了コードとして 1 を返します。エラー発生時には sys.exit("エラーメッセージ") と書くと、簡単にプログラムを終了することができます。

Since exit() ultimately "only" raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. Cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

バージョン 3.6 で変更: Python インタープリタが (バッファされたデータを標準ストリームに吐き出すときのエラーなどの) SystemExit を捕捉した後の後始末でエラーが起きた場合、終了ステータスは 120 に変更されます。

sys.flags

コマンドラインフラグの状態を表す 名前付きタプル です。各属性は読み出し専用になっています。

flags.debug

-d

flags.inspect

-i

flags.interactive

-i

flags.isolated

-I

flags.optimize

-O または -OO

flags.dont_write_bytecode

-B

flags.no_user_site

-s

flags.no_site

-S

flags.ignore_environment

-E

flags.verbose

-v

flags.bytes_warning

-b

flags.quiet

-q

flags.hash_randomization

-R

flags.dev_mode

-X dev (Python Development Mode)

flags.utf8_mode

-X utf8

flags.safe_path

-P

flags.int_max_str_digits

-X int_max_str_digits (integer string conversion length limitation)

flags.warn_default_encoding

-X warn_default_encoding

バージョン 3.2 で変更: 新しい -q 向けに quiet 属性が追加されました。

バージョン 3.2.3 で追加: hash_randomization 属性が追加されました。

バージョン 3.3 で変更: 廃止済みの division_warning 属性を削除しました。

バージョン 3.4 で変更: -I isolated フラグ向けに isolated 属性が追加されました。

バージョン 3.7 で変更: 新しい Python 開発モード 向けに dev_mode 属性が、新しい -X utf8 フラグ向けに utf8_mode 属性が追加されました。

バージョン 3.10 で変更: Added warn_default_encoding attribute for -X warn_default_encoding flag.

バージョン 3.11 で変更: Added the safe_path attribute for -P option.

バージョン 3.11 で変更: Added the int_max_str_digits attribute.

sys.float_info

float 型に関する情報を保持している 名前付きタプル です。精度と内部表現に関する低レベル情報を含んでいます。これらの値は 'C' 言語の標準ヘッダファイル float.h で定義されている様々な浮動小数点定数に対応しています。詳細は 1999 ISO/IEC C standard [C99] の 5.2.4.2.2 節 'Characteristics of floating types' を参照してください。

Attributes of the float_info named tuple

属性

float.h のマクロ

説明

float_info.epsilon

DBL_EPSILON

difference between 1.0 and the least value greater than 1.0 that is representable as a float.

math.ulp() を参照してください。

float_info.dig

DBL_DIG

The maximum number of decimal digits that can be faithfully represented in a float; see below.

float_info.mant_dig

DBL_MANT_DIG

Float precision: the number of base-radix digits in the significand of a float.

float_info.max

DBL_MAX

The maximum representable positive finite float.

float_info.max_exp

DBL_MAX_EXP

The maximum integer e such that radix**(e-1) is a representable finite float.

float_info.max_10_exp

DBL_MAX_10_EXP

The maximum integer e such that 10**e is in the range of representable finite floats.

float_info.min

DBL_MIN

The minimum representable positive normalized float.

Use math.ulp(0.0) to get the smallest positive denormalized representable float.

float_info.min_exp

DBL_MIN_EXP

The minimum integer e such that radix**(e-1) is a normalized float.

float_info.min_10_exp

DBL_MIN_10_EXP

The minimum integer e such that 10**e is a normalized float.

float_info.radix

FLT_RADIX

The radix of exponent representation.

float_info.rounds

FLT_ROUNDS

An integer representing the rounding mode for floating-point arithmetic. This reflects the value of the system FLT_ROUNDS macro at interpreter startup time:

  • -1: indeterminable

  • 0: toward zero

  • 1: to nearest

  • 2: toward positive infinity

  • 3: toward negative infinity

All other values for FLT_ROUNDS characterize implementation-defined rounding behavior.

The attribute sys.float_info.dig needs further explanation. If s is any string representing a decimal number with at most sys.float_info.dig significant digits, then converting s to a float and back again will recover a string representing the same decimal value:

>>> import sys
>>> sys.float_info.dig
15
>>> s = '3.14159265358979'    # decimal string with 15 significant digits
>>> format(float(s), '.15g')  # convert to float and back -> same value
'3.14159265358979'

ただし、文字列が有効桁数 sys.float_info.dig より大きい場合には、常に復元されるとは限りません:

>>> s = '9876543211234567'    # 16 significant digits is too many!
>>> format(float(s), '.16g')  # conversion changes value
'9876543211234568'
sys.float_repr_style

repr() 関数が浮動小数点数に対してどう振る舞うかを示す文字列です。この文字列が値 'short' を持てば、有限の浮動小数点数 x に対して、repr(x)float(repr(x)) == x を満たす短い文字列を返そうとします。これは、Python 3.1 以降での標準の振る舞いです。それ以外の場合、float_repr_style は値 'legacy' を持ち、repr(x) は 3.1 以前のバージョンの Python と同じように振る舞います。

バージョン 3.1 で追加.

sys.getallocatedblocks()

サイズに関わりなく、現在インタプリタから確保されたメモリブロックの数を返します。 この関数は主にメモリリークを追跡しバグを見付けるのに便利です。 インタプリタの内部的なキャッシュがあるために、呼び出しごとに結果が変わることがあります。より結果が予測しやすくなる _clear_type_cache()gc.collect() を呼ぶ必要があるかもしれません。

Python のあるビルドや実装が適切にこの情報を計算できない場合は、その代わりに getallocatedblocks() は 0 を返すことが許されています。

バージョン 3.4 で追加.

sys.getunicodeinternedsize()

Return the number of unicode objects that have been interned.

バージョン 3.12 で追加.

sys.getandroidapilevel()

ビルト時の Android のバージョンを整数で返します。

利用可能な環境: Android 。

バージョン 3.7 で追加.

sys.getdefaultencoding()

Unicode 実装で使用される現在のデフォルトエンコーディング名を返します。

sys.getdlopenflags()

Return the current value of the flags that are used for dlopen() calls. Symbolic names for the flag values can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).

sys.getfilesystemencoding()

Get the filesystem encoding: the encoding used with the filesystem error handler to convert between Unicode filenames and bytes filenames. The filesystem error handler is returned from getfilesystemencodeerrors().

最良の互換性のために、たとえファイル名の表現に bytes がサポートされていたとしても、全てのケースで str をファイル名に使うべきです。 ファイル名を受け取ったり返したりする関数は str と bytes をサポートし、すぐにシステムにとって好ましい表現に変換すべきです。

os.fsencode()os.fsdecode() を、正しいエンコーディングやエラーモードが使われていることを保証するために使うべきです。

The filesystem encoding and error handler are configured at Python startup by the PyConfig_Read() function: see filesystem_encoding and filesystem_errors members of PyConfig.

バージョン 3.2 で変更: getfilesystemencoding() の結果が None になることはなくなりました。

バージョン 3.6 で変更: Windows はもう 'mbcs' を返す保証は無くなりました。 より詳しいことは PEP 529 および _enablelegacywindowsfsencoding() を参照してください。

バージョン 3.7 で変更: Python UTF-8 モード が有効なら "utf-8" を返します。

sys.getfilesystemencodeerrors()

Get the filesystem error handler: the error handler used with the filesystem encoding to convert between Unicode filenames and bytes filenames. The filesystem encoding is returned from getfilesystemencoding().

os.fsencode()os.fsdecode() を、正しいエンコーディングやエラーモードが使われていることを保証するために使うべきです。

The filesystem encoding and error handler are configured at Python startup by the PyConfig_Read() function: see filesystem_encoding and filesystem_errors members of PyConfig.

バージョン 3.6 で追加.

sys.get_int_max_str_digits()

Returns the current value for the integer string conversion length limitation. See also set_int_max_str_digits().

バージョン 3.11 で追加.

sys.getrefcount(object)

object の参照数を返します。 object は (一時的に) getrefcount() からも参照されるため、参照数は予想される数よりも 1 多くなります。

Note that the returned value may not actually reflect how many references to the object are actually held. For example, some objects are "immortal" and have a very high refcount that does not reflect the actual number of references. Consequently, do not rely on the returned value to be accurate, other than a value of 0 or 1.

バージョン 3.12 で変更: Immortal objects have very large refcounts that do not match the actual number of references to the object.

sys.getrecursionlimit()

現在の最大再帰数を返します。最大再帰数は、Python インタプリタスタックの最大の深さです。この制限は Python プログラムが無限に再帰し、C スタックがオーバーフローしてクラッシュすることを防止するために設けられています。この値は setrecursionlimit() で指定することができます。

sys.getsizeof(object[, default])

object のサイズをバイト数で返します。object は任意の型のオブジェクトです。すべての組み込みオブジェクトは正しい値を返します。サードパーティー製の型については実装依存になります。

オブジェクトに直接起因するメモリ消費のみを表し、参照するオブジェクトは含みません。

オブジェクトがサイズを取得する手段を提供していない時は default が返されます。default が指定されていない場合は TypeError が送出されます。

getsizeof()object__sizeof__ メソッドを呼び出し、そのオブジェクトがガベージコレクタに管理されていた場合はガベージコレクタのオーバーヘッドを増やします。

getsizeof() を再帰的に使い、コンテナとその中身のサイズを割り出す例は、 再帰的な sizeof のレシピ を参照してください。

sys.getswitchinterval()

インタプリタの "スレッド切り替え間隔" を返します。setswitchinterval() を参照してください。

バージョン 3.2 で追加.

sys._getframe([depth])

コールスタックからフレームオブジェクトを返します。オプション引数 depth を指定すると、スタックのトップから depth だけ下のフレームオブジェクトを取得します。 depth がコールスタックよりも深ければ、 ValueError が発生します。 depth のデフォルト値は 0 で、この場合はコールスタックのトップのフレームを返します。

引数 frame監査イベント sys._getframe を送出します。

CPython 実装の詳細: この関数は、内部的かつ特殊な目的にのみ利用されるべきです。全ての Python 実装で存在することが保証されているわけではありません。

sys._getframemodulename([depth])

Return the name of a module from the call stack. If optional integer depth is given, return the module that many calls below the top of the stack. If that is deeper than the call stack, or if the module is unidentifiable, None is returned. The default for depth is zero, returning the module at the top of the call stack.

Raises an auditing event sys._getframemodulename with argument depth.

CPython 実装の詳細: この関数は、内部的かつ特殊な目的にのみ利用されるべきです。全ての Python 実装で存在することが保証されているわけではありません。

sys.getprofile()

setprofile() 関数で設定したプロファイラ関数を取得します。

sys.gettrace()

settrace() 関数で設定したトレース関数を取得します。

CPython 実装の詳細: gettrace() 関数は、デバッガ、プロファイラ、カバレッジツールなどの実装に使うことのみを想定しています。この関数の振る舞いは言語定義ではなく実装プラットフォームの一部です。そのため、他の Python 実装では利用できないかもしれません。

sys.getwindowsversion()

実行中の Windows バージョンを示す、名前付きタプルを返します。 名前の付いている要素は、 major, minor, build, platform, service_pack, service_pack_minor, service_pack_major, suite_mask, product_type, platform_version です。 service_pack は文字列を含み、 platform_version は 3-タプル、それ以外は整数です。 この構成要素には名前でもアクセスできるので、 sys.getwindowsversion()[0]sys.getwindowsversion().major と等価です。 先行のバージョンとの互換性のため、最初の 5 要素のみが添字の指定で取得できます。

platform will be 2 (VER_PLATFORM_WIN32_NT).

product_type は、以下の値のいずれかになります。:

定数

意味

1 (VER_NT_WORKSTATION)

システムはワークステーションです。

2 (VER_NT_DOMAIN_CONTROLLER)

システムはドメインコントローラです。

3 (VER_NT_SERVER)

システムはサーバですが、ドメインコントローラではありません。

This function wraps the Win32 GetVersionEx() function; see the Microsoft documentation on OSVERSIONINFOEX() for more information about these fields.

platform_version は、プロセスでエミュレートされているバージョンではなく、現在のオペレーティングシステムのメジャーバージョン、マイナーバージョン、ビルドナンバーを返します。 この関数は機能の検知ではなくロギングで使うためのものです。

注釈

platform_version derives the version from kernel32.dll which can be of a different version than the OS version. Please use platform module for achieving accurate OS version.

利用可能な環境: Windows 。

バージョン 3.2 で変更: 名前付きタプルに変更され、 service_pack_minor, service_pack_major, suite_mask, および product_type が追加されました。

バージョン 3.6 で変更: platform_version の追加

sys.get_asyncgen_hooks()

asyncgen_hooks オブジェクトを返します。このオブジェクトは (firstiter, finalizer) という形の namedtuple に似た形をしています。 firstiterfinalizer は両方とも None か、 asynchronous generator iterator を引数に取る関数と、イベントループが非同期ジェネレータの終了処理をスケジューリングするのに使う関数であることが求められます。

バージョン 3.6 で追加: より詳しくは PEP 525 を参照してください。

注釈

This function has been added on a provisional basis (see PEP 411 for details.)

sys.get_coroutine_origin_tracking_depth()

Get the current coroutine origin tracking depth, as set by set_coroutine_origin_tracking_depth().

バージョン 3.7 で追加.

注釈

This function has been added on a provisional basis (see PEP 411 for details.) Use it only for debugging purposes.

sys.hash_info

数値のハッシュ実装のパラメータを与える named tuple です。数値型のハッシュ化についての詳細は 数値型のハッシュ化 を参照してください。

hash_info.width

The width in bits used for hash values

hash_info.modulus

The prime modulus P used for numeric hash scheme

hash_info.inf

The hash value returned for a positive infinity

hash_info.nan

(This attribute is no longer used)

hash_info.imag

The multiplier used for the imaginary part of a complex number

hash_info.algorithm

The name of the algorithm for hashing of str, bytes, and memoryview

hash_info.hash_bits

The internal output size of the hash algorithm

hash_info.seed_bits

The size of the seed key of the hash algorithm

バージョン 3.2 で追加.

バージョン 3.4 で変更: algorithmhash_bitsseed_bits を追加

sys.hexversion

単精度整数にエンコードされたバージョン番号。この値は新バージョン(正規リリース以外であっても)ごとにかならず増加します。例えば、Python 1.5.2 以降でのみ動作するプログラムでは、以下のようなチェックを行います。

if sys.hexversion >= 0x010502F0:
    # use some advanced feature
    ...
else:
    # use an alternative implementation or warn the user
    ...

hexversionhex() 関数を使って 16 進数に変換しなければ値の意味を持ちません。より読みやすいバージョン番号が必要な場合には named tuple sys.version_info を使用してください。

hexversion のより詳しい情報については API と ABI のバージョニング を参照してください。

sys.implementation

現在起動している Python インタプリタに関する情報が格納されたオブジェクトです。すべての Python 実装において、以下の属性が存在することが要求されています。

name は実装の識別子です (例: 'cpython')。実際の文字列は Python 実装によって定義されますが、小文字であることが保証されています。

versionsys.version_info と同じ形式の、Python 実装 のバージョンを表す名前付きタプルです。これは現在起動しているインタプリタ固有のバージョンを意味します。sys.version_info は Python 言語 のバージョンであり、これはそのバージョンに準拠した 実装 のバージョンです。例えば、PyPy 1.8 の sys.implementation.versionsys.version_info(1, 8, 0, 'final', 0) になるのに対し、 sys.version_infosys.version_info(2, 7, 2, 'final', 0) になります。CPython は、それがリファレンス実装であるため、両者は同じ値になります。

hexversionsys.hexversion と同形式の、16 進数での実装のバージョンです。

cache_tag は、キャッシュされたモジュールのファイル名に使用されるタグです。慣例により、これは実装名とバージョンを組み合わせた文字列になります (例: 'cpython-33') が、Python 実装はその他の適切な値を使う場合があります。cache_tagNone が設定された場合、モジュールのキャッシングが無効になっていることを示します。

sys.implementation には Python 実装固有の属性を追加することができます。それら非標準属性の名前はアンダースコアから始めなくてはならず、そしてここでは説明されません。その内容に関係なく、sys.implementation はインタプリタ起動中や実装のバージョン間で変更することはありません (ただし Python 言語のバージョン間についてはその限りではありません)。詳細は PEP 421 を参照してください。

バージョン 3.3 で追加.

注釈

The addition of new required attributes must go through the normal PEP process. See PEP 421 for more information.

sys.int_info

Python における整数の内部表現に関する情報を保持する、named tuple です。この属性は読み出し専用です。

int_info.bits_per_digit

The number of bits held in each digit. Python integers are stored internally in base 2**int_info.bits_per_digit.

int_info.sizeof_digit

The size in bytes of the C type used to represent a digit.

int_info.default_max_str_digits

The default value for sys.get_int_max_str_digits() when it is not otherwise explicitly configured.

int_info.str_digits_check_threshold

The minimum non-zero value for sys.set_int_max_str_digits(), PYTHONINTMAXSTRDIGITS, or -X int_max_str_digits.

バージョン 3.1 で追加.

バージョン 3.11 で変更: Added default_max_str_digits and str_digits_check_threshold.

sys.__interactivehook__

この属性が存在する場合、インタープリタが 対話モード で起動したときに値は (引数なしで) 自動的に呼ばれます。これは PYTHONSTARTUP ファイルの読み込み後に行われるため、それにこのフックを設定することが出来ます。site モジュールで 設定します

引数 hook を指定して 監査イベント cpython.run_interactivehook を送出します。

バージョン 3.4 で追加.

sys.intern(string)

string を "隔離" された文字列のテーブルに入力し、隔離された文字列を返します -- この文字列は string 自体かコピーです。隔離された文字列は辞書検索のパフォーマンスを少しだけ向上させるのに有効です -- 辞書中のキーが隔離されており、検索するキーが隔離されている場合、(ハッシュ化後の) キーの比較は文字列の比較ではなくポインタの比較で行うことができるからです。通常、Python プログラム内で利用されている名前は自動的に隔離され、モジュール、クラス、またはインスタンス属性を保持するための辞書は隔離されたキーを持っています。

隔離された文字列はイモータルではありません。その恩恵を受けるためには intern() の返り値への参照を維持しなくてはなりません。

sys.is_finalizing()

Return True if the Python interpreter is shutting down, False otherwise.

バージョン 3.5 で追加.

sys.last_exc

This variable is not always defined; it is set to the exception instance when an exception is not handled and the interpreter prints an error message and a stack traceback. Its intended use is to allow an interactive user to import a debugger module and engage in post-mortem debugging without having to re-execute the command that caused the error. (Typical use is import pdb; pdb.pm() to enter the post-mortem debugger; see pdb module for more information.)

バージョン 3.12 で追加.

sys.last_type
sys.last_value
sys.last_traceback

These three variables are deprecated; use sys.last_exc instead. They hold the legacy representation of sys.last_exc, as returned from exc_info() above.

sys.maxsize

Py_ssize_t 型の変数が取りうる最大値を示す整数です。通常、32 ビットプラットフォームでは 2**31 - 1、64 ビットプラットフォームでは 2**63 - 1 になります。

sys.maxunicode

Unicode コードポイントの最大値を示す整数、すなわち 1114111 (16 進数で 0x10FFFF) です。

バージョン 3.3 で変更: PEP 393 以前は、オプション設定にUnicode文字の保存形式がUCS-2とUCS-4のどちらを指定したかによって、 sys.maxunicode の値は 0xFFFF0x10FFFF になっていました。

sys.meta_path

A list of meta path finder objects that have their find_spec() methods called to see if one of the objects can find the module to be imported. By default, it holds entries that implement Python's default import semantics. The find_spec() method is called with at least the absolute name of the module being imported. If the module to be imported is contained in a package, then the parent package's __path__ attribute is passed in as a second argument. The method returns a module spec, or None if the module cannot be found.

参考

importlib.abc.MetaPathFinder

The abstract base class defining the interface of finder objects on meta_path.

importlib.machinery.ModuleSpec

The concrete class which find_spec() should return instances of.

バージョン 3.4 で変更: Module specs were introduced in Python 3.4, by PEP 451.

バージョン 3.12 で変更: Removed the fallback that looked for a find_module() method if a meta_path entry didn't have a find_spec() method.

sys.modules

This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail. If you want to iterate over this global dictionary always use sys.modules.copy() or tuple(sys.modules) to avoid exceptions as its size may change during iteration as a side effect of code or activity in other threads.

sys.orig_argv

The list of the original command line arguments passed to the Python executable.

The elements of sys.orig_argv are the arguments to the Python interpreter, while the elements of sys.argv are the arguments to the user's program. Arguments consumed by the interpreter itself will be present in sys.orig_argv and missing from sys.argv.

バージョン 3.10 で追加.

sys.path

モジュールを検索するパスを示す文字列のリスト。 PYTHONPATH 環境変数と、インストール時に指定したデフォルトパスで初期化されます。

By default, as initialized upon program startup, a potentially unsafe path is prepended to sys.path (before the entries inserted as a result of PYTHONPATH):

  • python -m module command line: prepend the current working directory.

  • python script.py command line: prepend the script's directory. If it's a symbolic link, resolve symbolic links.

  • python -c code and python (REPL) command lines: prepend an empty string, which means the current working directory.

To not prepend this potentially unsafe path, use the -P command line option or the PYTHONSAFEPATH environment variable.

プログラムはその目的のために、このリストを自由に修正できます。文字列だけが sys.path に追加でき、 ほかの全てのデータ型はインポート中に無視されます。

参考

  • site モジュールのドキュメントで、 .pth ファイルを使って sys.path を拡張する方法を解説しています。

sys.path_hooks

path を引数にとって、その path に対する finder の作成を試みる呼び出し可能オブジェクトのリスト。 finder の作成に成功したら、その呼出可能オブジェクトのは finder を返します。失敗した場合は、 ImportError を発生させます。

オリジナルの仕様は PEP 302 を参照してください。

sys.path_importer_cache

finder オブジェクトのキャッシュ機能を果たす辞書です。キーは sys.path_hooks に渡されているパスで、値は見つかった finder になります。パスが正常なファイルシステムパスであり、finder が sys.path_hooks 上に見つからない場合は None が格納されます。

オリジナルの仕様は PEP 302 を参照してください。

sys.platform

プラットフォームを識別する文字列で、sys.path にプラットフォーム固有のサブディレクトリを追加する場合などに利用します。

Linux と AIX を除く Unix システムでは、uname -s が返す小文字の OS 名に uname -r が返すバージョン名の先頭を追加したものになります (例: 'sunos5''freebsd8')。この値は Python がビルドされた時点のもの です。システム固有のバージョンをテストする場合を除き、以下のような用法で使うことを推奨します:

if sys.platform.startswith('freebsd'):
    # FreeBSD-specific code here...
elif sys.platform.startswith('linux'):
    # Linux-specific code here...
elif sys.platform.startswith('aix'):
    # AIX-specific code here...

その他のシステムでは以下の値になります:

システム

platform の値

AIX

'aix'

Emscripten

'emscripten'

Linux

'linux'

WASI

'wasi'

Windows

'win32'

Windows/Cygwin

'cygwin'

macOS

'darwin'

バージョン 3.3 で変更: On Linux, sys.platform doesn't contain the major version anymore. It is always 'linux', instead of 'linux2' or 'linux3'. Since older Python versions include the version number, it is recommended to always use the startswith idiom presented above.

バージョン 3.8 で変更: On AIX, sys.platform doesn't contain the major version anymore. It is always 'aix', instead of 'aix5' or 'aix7'. Since older Python versions include the version number, it is recommended to always use the startswith idiom presented above.

参考

os.name has a coarser granularity. os.uname() gives system-dependent version information.

platform モジュールはシステムの詳細な識別情報をチェックする機能を提供しています。

sys.platlibdir

Name of the platform-specific library directory. It is used to build the path of standard library and the paths of installed extension modules.

It is equal to "lib" on most platforms. On Fedora and SuSE, it is equal to "lib64" on 64-bit platforms which gives the following sys.path paths (where X.Y is the Python major.minor version):

  • /usr/lib64/pythonX.Y/: Standard library (like os.py of the os module)

  • /usr/lib64/pythonX.Y/lib-dynload/: C extension modules of the standard library (like the errno module, the exact filename is platform specific)

  • /usr/lib/pythonX.Y/site-packages/ (always use lib, not sys.platlibdir): Third-party modules

  • /usr/lib64/pythonX.Y/site-packages/: C extension modules of third-party packages

バージョン 3.9 で追加.

sys.prefix

A string giving the site-specific directory prefix where the platform independent Python files are installed; on Unix, the default is /usr/local. This can be set at build time with the --prefix argument to the configure script. See インストールパス for derived paths.

注釈

仮想環境 で起動されている場合、この値は site.py によって仮想環境を示すよう変更されます。実際の Python のインストール先は base_prefix から取得できます。

sys.ps1
sys.ps2

インタプリタの一次プロンプト、二次プロンプトを指定する文字列。対話モードで実行中のみ定義され、初期値は '>>> ''... ' です。文字列以外のオブジェクトを指定した場合、インタプリタが対話コマンドを読み込むごとにオブジェクトの str() を評価します。この機能は、動的に変化するプロンプトを実装する場合に利用します。

sys.setdlopenflags(n)

Set the flags used by the interpreter for dlopen() calls, such as when the interpreter loads extension modules. Among other things, this will enable a lazy resolving of symbols when importing a module, if called as sys.setdlopenflags(0). To share symbols across extension modules, call as sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag values can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).

sys.set_int_max_str_digits(maxdigits)

Set the integer string conversion length limitation used by this interpreter. See also get_int_max_str_digits().

バージョン 3.11 で追加.

sys.setprofile(profilefunc)

Set the system's profile function, which allows you to implement a Python source code profiler in Python. See chapter Python プロファイラ for more information on the Python profiler. The system's profile function is called similarly to the system's trace function (see settrace()), but it is called with different events, for example it isn't called for each executed line of code (only on call and return, but the return event is reported even when an exception has been set). The function is thread-specific, but there is no way for the profiler to know about context switches between threads, so it does not make sense to use this in the presence of multiple threads. Also, its return value is not used, so it can simply return None. Error in the profile function will cause itself unset.

注釈

The same tracing mechanism is used for setprofile() as settrace(). To trace calls with setprofile() inside a tracing function (e.g. in a debugger breakpoint), see call_tracing().

Profile関数は 3 個の引数、frameevent、および arg を受け取る必要があります。frame は現在のスタックフレームです。event は文字列で、'call', 'return', 'c_call', 'c_return', 'c_exception' のどれかが渡されます。arg はイベントの種類によって異なります。

event には以下の意味があります。

'call'

関数が呼び出された(もしくは、何かのコードブロックに入った)。プロファイル関数が呼ばれる。 argNone が渡される。

'return'

関数(あるいは別のコードブロック)から戻ろうとしている。プロファイル関数が呼ばれる。 arg は返されようとしている値、または、このイベントが例外が送出されることによって起こったなら None

'c_call'

C 関数(拡張関数かビルトイン関数)が呼ばれようとしている。 arg は C 関数オブジェクト。

'c_return'

C 関数から戻った。 arg は C の関数オブジェクト。

'c_exception'

C 関数が例外を発生させた。 arg は C の関数オブジェクト。

引数無しで 監査イベント sys.setprofile を送出します。

sys.setrecursionlimit(limit)

Python インタプリタの、スタックの最大の深さを limit に設定します。この制限は Python プログラムが無限に再帰し、 C スタックがオーバーフローしてクラッシュすることを防止するために設けられています。

limit の最大値はプラットフォームによって異なります。深い再帰処理が必要な場合にはプラットフォームがサポートしている範囲内でより大きな値を指定することができますが、この値が大きすぎればクラッシュするので注意が必要です。

If the new limit is too low at the current recursion depth, a RecursionError exception is raised.

バージョン 3.5.1 で変更: A RecursionError exception is now raised if the new limit is too low at the current recursion depth.

sys.setswitchinterval(interval)

インタプリタのスレッド切り替え間隔を秒で指定します。この浮動小数点値が、並列に動作しているPythonスレッドに割り当てられたタイムスライスの理想的な処理時間です。特に長時間実行される内部関数やメソッドが実行されたとき、実際の値はより高くなることがあります。また、どのスレッドがスレッド切り替え間隔の終わりにスケジュールされる(次に実行される)かはオペレーティングシステムが決定します。インタプリタは自身のスケジューラを持ちません。

バージョン 3.2 で追加.

sys.settrace(tracefunc)

Set the system's trace function, which allows you to implement a Python source code debugger in Python. The function is thread-specific; for a debugger to support multiple threads, it must register a trace function using settrace() for each thread being debugged or use threading.settrace().

Trace関数は 3 個の引数、frameevent、および arg を受け取る必要があります。frame は現在のスタックフレームです。event は文字列で、'call', 'line', 'return', 'exception', 'opcode' のどれかが渡されます。arg はイベントの種類によって異なります。

trace 関数は (event'call' を渡された状態で) 新しいローカルスコープに入るたびに呼ばれます。この場合、新しいスコープで利用するローカルの trace 関数への参照か、そのスコープを trace しないのであれば None を返します。

The local trace function should return a reference to itself, or to another function which would then be used as the local trace function for the scope.

If there is any error occurred in the trace function, it will be unset, just like settrace(None) is called.

注釈

Tracing is disabled while calling the trace function (e.g. a function set by settrace()). For recursive tracing see call_tracing().

event には以下の意味があります。

'call'

関数が呼び出された(もしくは、何かのコードブロックに入った)。グローバルの trace 関数が呼ばれる。 argNone が渡される。戻り値はローカルの trace 関数。

'line'

The interpreter is about to execute a new line of code or re-execute the condition of a loop. The local trace function is called; arg is None; the return value specifies the new local trace function. See Objects/lnotab_notes.txt for a detailed explanation of how this works. Per-line events may be disabled for a frame by setting f_trace_lines to False on that frame.

'return'

関数(あるいは別のコードブロック)から戻ろうとしている。ローカルの trace 関数が呼ばれる。 arg は返されようとしている値、または、このイベントが例外が送出されることによって起こったなら None 。 trace 関数の戻り値は無視される。

'exception'

例外が発生した。ローカルの trace 関数が呼ばれる。 arg(exception, value, traceback) のタプル。戻り値は新しいローカルの trace 関数。

'opcode'

The interpreter is about to execute a new opcode (see dis for opcode details). The local trace function is called; arg is None; the return value specifies the new local trace function. Per-opcode events are not emitted by default: they must be explicitly requested by setting f_trace_opcodes to True on the frame.

例外が呼び出しチェインを辿って伝播していくことに注意してください。 'exception' イベントは各レベルで発生します。

For more fine-grained usage, it's possible to set a trace function by assigning frame.f_trace = tracefunc explicitly, rather than relying on it being set indirectly via the return value from an already installed trace function. This is also required for activating the trace function on the current frame, which settrace() doesn't do. Note that in order for this to work, a global tracing function must have been installed with settrace() in order to enable the runtime tracing machinery, but it doesn't need to be the same tracing function (e.g. it could be a low overhead tracing function that simply returns None to disable itself immediately on each frame).

code と frame オブジェクトについては、 標準型の階層 を参照してください。

引数無しで 監査イベント sys.settrace を送出します。

CPython 実装の詳細: settrace() 関数は、デバッガ、プロファイラ、カバレッジツール等で使うためだけのものです。この関数の挙動は言語定義よりも実装プラットフォームの分野の問題で、全ての Python 実装で利用できるとは限りません。

バージョン 3.7 で変更: 'opcode' event type added; f_trace_lines and f_trace_opcodes attributes added to frames

バージョン 3.12 で変更: 'opcode' event will only be emitted if f_trace_opcodes of at least one frame has been set to True before settrace() is called. This behavior will be changed back in 3.13 to be consistent with previous versions.

sys.set_asyncgen_hooks([firstiter] [, finalizer])

Accepts two optional keyword arguments which are callables that accept an asynchronous generator iterator as an argument. The firstiter callable will be called when an asynchronous generator is iterated for the first time. The finalizer will be called when an asynchronous generator is about to be garbage collected.

引数無しで 監査イベント sys.set_asyncgen_hooks_firstiter を送出します。

引数無しで 監査イベント sys.set_asyncgen_hooks_finalizer を送出します。

Two auditing events are raised because the underlying API consists of two calls, each of which must raise its own event.

バージョン 3.6 で追加: See PEP 525 for more details, and for a reference example of a finalizer method see the implementation of asyncio.Loop.shutdown_asyncgens in Lib/asyncio/base_events.py

注釈

This function has been added on a provisional basis (see PEP 411 for details.)

sys.set_coroutine_origin_tracking_depth(depth)

Allows enabling or disabling coroutine origin tracking. When enabled, the cr_origin attribute on coroutine objects will contain a tuple of (filename, line number, function name) tuples describing the traceback where the coroutine object was created, with the most recent call first. When disabled, cr_origin will be None.

To enable, pass a depth value greater than zero; this sets the number of frames whose information will be captured. To disable, pass set depth to zero.

This setting is thread-specific.

バージョン 3.7 で追加.

注釈

This function has been added on a provisional basis (see PEP 411 for details.) Use it only for debugging purposes.

sys.activate_stack_trampoline(backend, /)

Activate the stack profiler trampoline backend. The only supported backend is "perf".

バージョン 3.12 で追加.

sys.deactivate_stack_trampoline()

Deactivate the current stack profiler trampoline backend.

If no stack profiler is activated, this function has no effect.

バージョン 3.12 で追加.

sys.is_stack_trampoline_active()

Return True if a stack profiler trampoline is active.

バージョン 3.12 で追加.

sys._enablelegacywindowsfsencoding()

Changes the filesystem encoding and error handler to 'mbcs' and 'replace' respectively, for consistency with versions of Python prior to 3.6.

This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING environment variable before launching Python.

See also sys.getfilesystemencoding() and sys.getfilesystemencodeerrors().

利用可能な環境: Windows 。

バージョン 3.6 で追加: より詳しくは PEP 529 を参照してください。

sys.stdin
sys.stdout
sys.stderr

インタプリタが使用する、それぞれ標準入力、標準出力、および標準エラー出力の ファイルオブジェクト です:

  • stdin は (input() の呼び出しも含む) すべての対話型入力に使われます。

  • stdoutprint() および expression 文の出力と、input() のプロンプトに使用されます。

  • インタプリタ自身のプロンプトおよびエラーメッセージは stderr に出力されます。

これらのストリームは open() が返すような通常の テキストファイル です。引数は以下のように選択されます:

  • The encoding and error handling are is initialized from PyConfig.stdio_encoding and PyConfig.stdio_errors.

    On Windows, UTF-8 is used for the console device. Non-character devices such as disk files and pipes use the system locale encoding (i.e. the ANSI codepage). Non-console character devices such as NUL (i.e. where isatty() returns True) use the value of the console input and output codepages at startup, respectively for stdin and stdout/stderr. This defaults to the system locale encoding if the process is not initially attached to a console.

    The special behaviour of the console can be overridden by setting the environment variable PYTHONLEGACYWINDOWSSTDIO before starting Python. In that case, the console codepages are used as for any other character device.

    Under all platforms, you can override the character encoding by setting the PYTHONIOENCODING environment variable before starting Python or by using the new -X utf8 command line option and PYTHONUTF8 environment variable. However, for the Windows console, this only applies when PYTHONLEGACYWINDOWSSTDIO is also set.

  • When interactive, the stdout stream is line-buffered. Otherwise, it is block-buffered like regular text files. The stderr stream is line-buffered in both cases. You can make both streams unbuffered by passing the -u command-line option or setting the PYTHONUNBUFFERED environment variable.

バージョン 3.9 で変更: Non-interactive stderr is now line-buffered instead of fully buffered.

注釈

標準ストリームにバイナリーデータの読み書きを行うには下位のバイナリー buffer オブジェクトを使用してください。例えば bytesstdout に書き出す場合は sys.stdout.buffer.write(b'abc') を使用してください。

However, if you are writing a library (and do not control in which context its code will be executed), be aware that the standard streams may be replaced with file-like objects like io.StringIO which do not support the buffer attribute.

sys.__stdin__
sys.__stdout__
sys.__stderr__

それぞれ起動時の stdin, stderr, stdout の値を保存しています。終了処理時に利用されます。また、 sys.std* オブジェクトが(訳注:別のファイルライクオブジェクトに)リダイレクトされている場合でも、実際の標準ストリームへの出力に利用できます。

また、標準ストリームが壊れたオブジェクトに置き換えられた場合に、動作する実際のファイルを復元するために利用することもできます。しかし、明示的に置き換え前のストリームを保存しておき、そのオブジェクトを復元する事を推奨します。

注釈

一部の条件下では、stdin, stdout, stderr も、オリジナルの __stdin__, __stdout__, __stderr__None になることがあります。これはコンソールに接続しない Windows GUI アプリケーションであり、かつ pythonw で起動された Python アプリケーションが該当します。

sys.stdlib_module_names

A frozenset of strings containing the names of standard library modules.

It is the same on all platforms. Modules which are not available on some platforms and modules disabled at Python build are also listed. All module kinds are listed: pure Python, built-in, frozen and extension modules. Test modules are excluded.

For packages, only the main package is listed: sub-packages and sub-modules are not listed. For example, the email package is listed, but the email.mime sub-package and the email.message sub-module are not listed.

See also the sys.builtin_module_names list.

バージョン 3.10 で追加.

sys.thread_info

スレッドの実装に関する情報が格納された named tuple です。

thread_info.name

The name of the thread implementation:

  • "nt": Windows threads

  • "pthread": POSIX threads

  • "pthread-stubs": stub POSIX threads (on WebAssembly platforms without threading support)

  • "solaris": Solaris threads

thread_info.lock

The name of the lock implementation:

  • "semaphore": a lock uses a semaphore

  • "mutex+cond": a lock uses a mutex and a condition variable

  • None この情報が不明の場合

thread_info.version

The name and version of the thread library. It is a string, or None if this information is unknown.

バージョン 3.3 で追加.

sys.tracebacklimit

捕捉されない例外が発生した時、出力されるトレースバック情報の最大レベル数を指定する整数値(デフォルト値は 1000)。 0 以下の値が設定された場合、トレースバック情報は出力されず例外型と例外値のみが出力されます。

sys.unraisablehook(unraisable, /)

Handle an unraisable exception.

Called when an exception has occurred but there is no way for Python to handle it. For example, when a destructor raises an exception or during garbage collection (gc.collect()).

The unraisable argument has the following attributes:

  • exc_type: Exception type.

  • exc_value: Exception value, can be None.

  • exc_traceback: Exception traceback, can be None.

  • err_msg: Error message, can be None.

  • object: Object causing the exception, can be None.

The default hook formats err_msg and object as: f'{err_msg}: {object!r}'; use "Exception ignored in" error message if err_msg is None.

sys.unraisablehook() can be overridden to control how unraisable exceptions are handled.

参考

excepthook() which handles uncaught exceptions.

警告

Storing exc_value using a custom hook can create a reference cycle. It should be cleared explicitly to break the reference cycle when the exception is no longer needed.

Storing object using a custom hook can resurrect it if it is set to an object which is being finalized. Avoid storing object after the custom hook completes to avoid resurrecting objects.

引数 hook, unraisable を指定して 監査イベント sys.unraisablehook を送出します。

バージョン 3.8 で追加.

sys.version

Python インタプリタのバージョン番号の他、ビルド番号や使用コンパイラなどの情報を示す文字列です。この文字列は Python 対話型インタプリタが起動した時に表示されます。バージョン情報はここから抜き出さずに、 version_info および platform が提供する関数を使って下さい。

sys.api_version

使用中のインタプリタの C API バージョン。 Python と拡張モジュール間の不整合をデバッグする場合などに利用できます。

sys.version_info

バージョン番号を示す 5 要素タプル:major, minor, micro, releaselevel, serialreleaselevel 以外は全て整数です。 releaselevel の値は、 'alpha', 'beta', 'candidate', 'final' の何れかです。 Python 2.0 の version_info は、 (2, 0, 0, 'final', 0) となります。構成要素には名前でもアクセスできるので、 sys.version_info[0]sys.version_info.major と等価、などになります。

バージョン 3.1 で変更: 名前を使った要素アクセスがサポートされました。

sys.warnoptions

この値は、warnings フレームワーク内部のみ使用され、変更することはできません。詳細は warnings を参照してください。

sys.winver

The version number used to form registry keys on Windows platforms. This is stored as string resource 1000 in the Python DLL. The value is normally the major and minor versions of the running Python interpreter. It is provided in the sys module for informational purposes; modifying this value has no effect on the registry keys used by Python.

利用可能な環境: Windows 。

sys.monitoring

Namespace containing functions and constants for register callbacks and controlling monitoring events. See sys.monitoring for details.

sys._xoptions

コマンドラインオプション -X で渡された様々な実装固有のフラグの辞書です。オプション名にはその値が明示されていればそれが、それ以外の場合は True がマップされます。例えば:

$ ./python -Xa=b -Xc
Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys._xoptions
{'a': 'b', 'c': True}

CPython 実装の詳細: この -X によって渡されたオプションにアクセスする方法は CPython 固有です。他の実装ではそれらは他の意味でエクスポートされるか、あるいは何もしません。

バージョン 3.2 で追加.

出典

[C99]

ISO/IEC 9899:1999. "Programming languages -- C." この標準のパブリックドラフトが参照できます: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf