1. 程式人生 > >4Python標準庫系列之sys模塊

4Python標準庫系列之sys模塊

maintained provides always access 解釋器

Python標準庫系列之sys模塊


This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.


sys模塊用於提供對解釋器相關的操作

模塊方法解釋說明
sys.argv傳遞到Python腳本的命令行參數列表,第一個元素是程序本身路徑
sys.executable返回Python解釋器在當前系統中的絕對路徑
sys.exit([arg])程序中間的退出,arg=0為正常退出
sys.path返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform返回操作系統平臺名稱,Linux是linux2,Windows是win32
sys.stdout.write(str)輸出的時候把換行符\n去掉
val = sys.stdin.readline()[:-1]拿到的值去掉\n換行符
sys.version獲取Python解釋程序的版本信息
  • 位置參數

[[email protected] ~]# cat scripts.py    
#!/usr/bin/env python
import sys
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])
[[email protected]
/* */ ~]# python scripts.py canshu1 canshu2 scripts.py canshu1 canshu

sys.argv[0]代表腳本本身,如果用相對路徑執行則會顯示腳本的名稱,如果是絕對路徑則會顯示腳本名稱;

  • 程序中途退出

python在默認執行腳本的時候會由頭執行到尾,然後自動退出,但是如果需要中途退出程序, 你可以調用sys.exit函數,它帶有一個可選的整數參數返回給調用它的程序. 這意味著你可以在主程序中捕獲對sys.exit的調用。(註:0是正常退出,其他為不正常,可拋異常事件供捕獲!)

原腳本和輸出的結果:

[[email protected]
*/ sys]# cat sys-03.py #!/usr/bin/python # _*_ coding:utf-8 _*_ import sys print "hello word!" print "your is pythoner" [[email protected] sys]# python sys-03.py hello word! your is pythoner

執行腳本之後會輸出,下面這兩段內容:

hello word!
your is pythoner

然後我們在print "hello word!"之後讓程序退出不執行print "your is pythoner"

[[email protected] sys]# cat sys-03.py 
#!/usr/bin/python
# _*_ coding:utf-8 _*_

import sys

print "hello word!"
sys.exit()
print "your is pythoner"
[[email protected] sys]# python sys-03.py 
hello word!

PS:sys.exit從python程序中退出,將會產生一個systemExit異常,可以為此做些清除除理的工作。這個可選參數默認正常退出狀態是0,以數值為參數的範圍為:0-127。其他的數值為非正常退出,還有另一種類型,在這裏展現的是strings對象類型。

  • 獲取模塊路徑

在使用Python中用import_import_導入模塊的時候,那Python是怎麽判斷有沒有這個模塊的呢?
其實就是根據sys.path的路徑來搜索你導入模塊的名稱。

 >>> for i in sys.path:
 ...  print(i)
 ...
 
C:\Python35\lib\site-packages\pip-8.1.1-py3.5.egg
C:\Python35\python35.zip
C:\Python35\DLLs
C:\Python35\lib
C:\Python35
C:\Python35\lib\site-packages
  • 獲取當前系統平臺

Linux

 >>> import sys
 >>> sys.platform
‘linux2‘

Windows

 >>> import sys
 >>> sys.platform
‘win32‘

#Python標準庫 #Sys


4Python標準庫系列之sys模塊