ホームページ  >  記事  >  バックエンド開発  >  Python sys モジュールの基本的な紹介

Python sys モジュールの基本的な紹介

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼オリジナル
2019-06-14 14:47:037769ブラウズ

1: sys は Python の組み込みモジュールです。

import ステートメントを使用して sys モジュールに入ります。

関連する推奨事項: 「python ビデオ

Python sys モジュールの基本的な紹介

import sys を実行すると、sys 内のディレクトリに Python がリストされます。パス変数 sys モジュール ファイルを検索します。次に、このモジュールのメイン ブロック内のステートメントを実行して初期化すると、モジュールを使用できるようになります。

2: sys モジュールの共通関数

dir() メソッドを使用して、モジュールで利用可能なメソッドを表示できます。結果は次のとおりです。 sys.argv はプログラムの外部からプログラムにパラメータを渡す実装です

sys.argv 変数はコマンド ライン パラメータ リストを含む文字列で、コマンド ラインを使用してパラメータをプログラムに渡します。その中で、スクリプトの名前は常に sys.argv リストの最初のパラメータになります。

(2) sys.path には、入力モジュールのディレクトリ名のリストが含まれます。

指定したモジュール検索パスの文字列コレクションを取得 記述したモジュールを特定のパス配下に置くことで、プログラムにインポートする際に正しく検索できます。 module_name をインポートすると、sys.path のパスに基づいて module.name が検索されます。モジュールのパスをカスタマイズすることもできます。

sys.path.append("カスタム モジュール パス")

(3) sys.exit([arg]) プログラムの途中で終了します。arg=0 は通常の終了を意味します

通常、インタープリタは、実行がメイン プログラムの最後に達すると自動的に終了します。ただし、プログラムを途中で終了する必要がある場合は、呼び出し側に返されるオプションの整数パラメータを指定して sys.exit 関数を呼び出すことができます。 sys.exit への呼び出しはメイン プログラムでキャプチャされます。 (0 は正常終了を意味し、その他は例外です) もちろん、文字列パラメーターを使用して、失敗したエラー メッセージを示すこともできます。

(4) sys.modules

sys.modules はグローバル辞書で、Python の起動後にメモリにロードされます。プログラマが新しいモジュールをインポートするたびに、sys.modules はそのモジュールを自動的に記録します。モジュールが 2 回目にインポートされると、Python はそのモジュールを辞書で直接検索するため、プログラムが高速化されます。辞書にあるすべてのメソッドが含まれています。

(5) sys.getdefaultencoding() / sys.setdefaultencoding() / sys.getfilesystemencoding()

sys.getdefaultencoding()

システムの現在のエンコーディングを取得します。通常、デフォルトは ASCII です。

sys.setdefaultencoding()

システムのデフォルトのエンコーディングを設定します。dir (sys) の実行時にはこのメソッドは表示されません。インタープリタで実行が失敗した場合は、リロード (sys) を実行できます。 ) 最初に、setdefaultencoding('utf8') を実行すると、システムのデフォルトのエンコーディングが utf8 に設定されます。 (システムのデフォルトのエンコーディングの設定を参照)

sys.getfilesystemencoding()

ファイル システムで使用されるエンコーディングを取得します。Windows では 'mbcs'、mac では 'utf-8' を返します

(6) sys.stdin、sys.stdout、sys.stderr

stdin、stdout、および stderr 変数には、標準 I/O ストリームに対応するストリーム オブジェクトが含まれています。出力と印刷が要件を満たしていない場合、それらは必要なものです。それらを置き換えることもでき、出力と入力を他のデバイス (デバイス) にリダイレクトしたり、標準以外の方法で処理したりすることもできます。

(7) sys.platform

現在のシステム プラットフォームを取得します (win32、Linux など)。

3: 例

(1) sys.argv sys.path

$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', '_multiarch', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']

実行結果:

$ cat sys-test.py
 #!/usr/bin/python
import sys
print 'The command line arguments are:'
for i in sys.argv:
    print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'

(2) sys.exit

$ python sys-test.py my name is ubuntu 
The command line arguments are:
sys-test.py
my
name
is
ubuntu
The PYTHONPATH is ['/work/python-practice', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']

実行結果:

import sys
def exitfunc(value):
    print (value)
    sys.exit(0)
print("hello")
try:
    sys.exit(90)
except SystemExit as value:
    exitfunc(value)   
print("come?")

プログラムは最初に hello を出力し、次に exit(90) を実行し、例外をスローして値に 90 を渡します。値は渡された内容で実行されます。関数を実行し、90 を出力します。プログラムが終了します。次の「come?」はすでに終了しているため出力されませんが、このときexitfunc関数のsys.exit(0)を削除しておけば、「come?」が出力されるまでプログラムは実行され続けます。

(3) sys.modules

sys.modules.keys() はインポートされたすべてのモジュールのリストを返します

keys はモジュール名です

valuesモジュール

modules return path

hello
90

実行結果:

import sys
print(sys.modules.keys())
print("**************************************************************************")
print(sys.modules.values())
print("**************************************************************************")
print(sys.modules["os"])

(4) sys.stdin/sys.stdout/sys.stderr

stdin、stdout、stderr が含まれています Python のすべてのファイル属性オブジェクトは、Python の起動時にシェル環境の標準入力、出力、エラーに自動的に関連付けられます シェルでの Python プログラムの I/O リダイレクトは、次のように提供されます関係: Python プログラムは、stdin、stdout、stderr の読み取りおよび書き込み操作を内部オブジェクトに内部的にリダイレクトします。

標準入力

['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'abc', 'posixpath', '_weakrefset', 'errno', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__', '_warnings', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'warnings', 'UserDict', 'encodings.ascii', 'sys', 'codecs', '_sysconfigdata_nd', 'os.path', 'sitecustomize', 'signal', 'traceback', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']
*******************************************************************************
[<module &#39;copy_reg&#39; from &#39;/usr/lib/python2.7/copy_reg.pyc&#39;>, <module &#39;sre_compile&#39; from &#39;/usr/lib/python2.7/sre_compile.pyc&#39;>, <module &#39;_sre&#39; (built-in)>, <module &#39;encodings&#39; from &#39;/usr/lib/python2.7/encodings/__init__.pyc&#39;>, <module &#39;site&#39; from &#39;/usr/lib/python2.7/site.pyc&#39;>, <module &#39;__builtin__&#39; (built-in)>, <module &#39;sysconfig&#39; from &#39;/usr/lib/python2.7/sysconfig.pyc&#39;>, <module &#39;__main__&#39; from &#39;sys-test1.py&#39;>, None, <module &#39;abc&#39; from &#39;/usr/lib/python2.7/abc.pyc&#39;>, <module &#39;posixpath&#39; from &#39;/usr/lib/python2.7/posixpath.pyc&#39;>, <module &#39;_weakrefset&#39; from &#39;/usr/lib/python2.7/_weakrefset.pyc&#39;>, <module &#39;errno&#39; (built-in)>, None, <module &#39;sre_constants&#39; from &#39;/usr/lib/python2.7/sre_constants.pyc&#39;>, <module &#39;re&#39; from &#39;/usr/lib/python2.7/re.pyc&#39;>, <module &#39;_abcoll&#39; from &#39;/usr/lib/python2.7/_abcoll.pyc&#39;>, <module &#39;types&#39; from &#39;/usr/lib/python2.7/types.pyc&#39;>, <module &#39;_codecs&#39; (built-in)>, None, <module &#39;_warnings&#39; (built-in)>, <module &#39;genericpath&#39; from &#39;/usr/lib/python2.7/genericpath.pyc&#39;>, <module &#39;stat&#39; from &#39;/usr/lib/python2.7/stat.pyc&#39;>, <module &#39;zipimport&#39; (built-in)>, <module &#39;_sysconfigdata&#39; from &#39;/usr/lib/python2.7/_sysconfigdata.pyc&#39;>, <module &#39;warnings&#39; from &#39;/usr/lib/python2.7/warnings.pyc&#39;>, <module &#39;UserDict&#39; from &#39;/usr/lib/python2.7/UserDict.pyc&#39;>, <module &#39;encodings.ascii&#39; from &#39;/usr/lib/python2.7/encodings/ascii.pyc&#39;>, <module &#39;sys&#39; (built-in)>, <module &#39;codecs&#39; from &#39;/usr/lib/python2.7/codecs.pyc&#39;>, <module &#39;_sysconfigdata_nd&#39; from &#39;/usr/lib/python2.7/plat-x86_64-linux-gnu/_sysconfigdata_nd.pyc&#39;>, <module &#39;posixpath&#39; from &#39;/usr/lib/python2.7/posixpath.pyc&#39;>, <module &#39;sitecustomize&#39; from &#39;/usr/lib/python2.7/sitecustomize.pyc&#39;>, <module &#39;signal&#39; (built-in)>, <module &#39;traceback&#39; from &#39;/usr/lib/python2.7/traceback.pyc&#39;>, <module &#39;linecache&#39; from &#39;/usr/lib/python2.7/linecache.pyc&#39;>, <module &#39;posix&#39; (built-in)>, <module &#39;encodings.aliases&#39; from &#39;/usr/lib/python2.7/encodings/aliases.pyc&#39;>, <module &#39;exceptions&#39; (built-in)>, <module &#39;sre_parse&#39; from &#39;/usr/lib/python2.7/sre_parse.pyc&#39;>, <module &#39;os&#39; from &#39;/usr/lib/python2.7/os.pyc&#39;>, <module &#39;_weakref&#39; (built-in)>]
*******************************************************************************
<module &#39;os&#39; from &#39;/usr/lib/python2.7/os.pyc&#39;>
実行結果:
import sys
#print(&#39;Hi, %s!&#39; %input(&#39;Please enter your name: &#39;)) python3.*版本用input
print(&#39;Hi, %s!&#39; %raw_input(&#39;Please enter your name: &#39;)) #python2.*版本用raw_input
运行结果:
Please enter your name: er
Hi, er!
等同于:
 #!/usr/bin/python
import sys
print(&#39;Please enter your name:&#39;)
name=sys.stdin.readline()[:-1]
print(&#39;Hi, %s!&#39; %name)
标准输出
print(&#39;Hello World!\n&#39;)
等同于:
 #!/usr/bin/python
import sys
sys.stdout.write(&#39;output resule is good!\n&#39;)
其他实验
#!/usr/bin/python
import sys
for i in (sys.stdin, sys.stdout, sys.stderr):
    print(i)

以上がPython sys モジュールの基本的な紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。