首頁  >  文章  >  後端開發  >  python sys模組的基本介紹

python sys模組的基本介紹

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼原創
2019-06-14 14:47:037769瀏覽

1: sys是python自帶模組. 

利用 import 語句輸入sys 模組。

相關推薦:《python影片

python sys模組的基本介紹

#當執行import sys後, python在sys.path 變數中所列目錄中尋找sys 模組檔。然後執行這個模組的主區塊中的語句進行初始化,然後就可以使用模組了 。

2: sys模組常見函數 

可以透過dir()方法查看模組中可用的方法. 結果如下, 很多我都沒有用過, 所以只是簡單介紹幾個自己用過的方法.

$ 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']

(1) sys.argv 實作從程式外部傳遞參數 

sys.argv 變數是一個包含了命令列參數的字串列表, 利用命令列想程式傳遞參數. 其中,腳本的名稱總是sys.argv 列表的第一個參數。

(2) sys.path 包含輸入模組的目錄名稱清單。 

取得指定模組搜尋路徑的字串集合,可以將寫好的模組放在得到的某個路徑下,就可以在程式中import時正確找到。當import導入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將自動記錄該模組。當第二次再導入該模組時,python會直接到字典中查找,從而加快了程式運行的速度。它擁有字典所擁有的一切方法.

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

sys.getdefaultencoding() 

#取得系統目前編碼,一般預設為ascii。

sys.setdefaultencoding() 

設定係統預設編碼,執行dir(sys)時不會看到這個方法,在解釋器中執行不通過,可以先執行reload(sys) ,在執行setdefaultencoding('utf8'),此時將系統預設編碼設為utf8。 (請參閱設定係統預設編碼) 

sys.getfilesystemencoding() 

取得檔案系統使用編碼方式,Windows下回傳'mbcs',mac下回傳'utf-8'

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

stdin , stdout , 以及stderr 變數包含與標準I/O 流對應的流物件. 如果需要更好地控制輸出, print 不能滿足你的要求, 它們就是你所需要的. 你也可以替換它們, 這時候你就可以重定向輸出和輸入到其它設備( device ), 或者以非標準的方式處理它們.

(7) sys.platform 

取得目前系統平台. 如:win32、Linux等。

3: 實例 

(1) sys.argv sys.path

$ 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'

執行結果:

$ 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']

(2) sys.exit

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
90

程式先印hello,在執行exit(90),拋異常把90傳給values,values在傳進函數中執行,印90程序退出。後面的”come?”因為已經退出所以不會被打印. 而此時如果把exitfunc函數裡面的sys.exit(0)去掉,那麼程式會繼續執行到輸出”come?”.

# (3) sys.modules 

sys.modules.keys() 傳回所有已匯入的模組清單 

keys是模組名稱 

#values是模組 

modules返迴路徑

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

運行結果: 

['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;>

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

#stdin,stdout,stderr在Python是檔案屬性物件, 他們在python啟動時自動與shell環境中的標準輸入, 輸出, 出錯相關. 而python程式在shell中的I/O重定向是有shell來提供的,與python本身沒有關係.python程式內部將stdin, stdout, stderr讀寫操作重定向到一個內部物件.

標準輸入##

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-test1.py
<open file &#39;<stdin>&#39;, mode &#39;r&#39; at 0x7fa4e630f0c0>
<open file &#39;<stdout>&#39;, mode &#39;w&#39; at 0x7fa4e630f150>
<open file &#39;<stderr>&#39;, mode &#39;w&#39; at 0x7fa4e630f1e0>

以上是python sys模組的基本介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn