1. 程式人生 > >python中的Sys模組

python中的Sys模組

Sys模組函式之多,我只能選取自己認為比較實用的一些函式列在此處。借馬雲找員工的說法,”找最合適的而不是最天才的”,這句話,我個人覺得在很多方面都能適應,學習也不在話下。Sys模組功能的確很多,但我們應該將重點放在那些功能才是最適合我們的,為此,我列的這些函式,就是我認為比較適合我以後開發的函式。
(1)sys.argv
很多人會想,我如何給我的程式在外部傳遞引數呢?這個,就可以實現。如:
Tesy.py
Import sys
Print sys.argv[number]
一般情況下,number為0是這個指令碼的名字,1,2…則為命令列下傳遞的引數.如:
Test.py指令碼內容:
import sys
 
print sys.argv[0]
print sys.argv[1]
print sys.argv[2]
print sys.argv[3]
那麼
[[email protected] scripts]# python test.py arg1 arg2 arg3
test.py
arg1
arg2
arg3
看到,對應的關係了嗎?還有,在python.org模組參考手冊說,如果在命令列下選用-c那麼argv[0]= -c 看下,
[
[email protected]
scripts]# python -c "import sys;print sys.argv[0];print sys.argv[1]" arg1
-c
arg1
如果大家不明白,可以參考下man python
SYNOPSIS
       python [ -d ] [ -E ] [ -h ] [ -i ] [ -m module-name ] [ -O ]
              [ -Q argument ] [ -S ] [ -t ] [ -u ]
              [ -v ] [ -V ] [ -W argument ] [ -x ]
              [ -c command | script | - ] [ arguments ]
(2)sys.platform
大家都知道,當今的程式比較流行的是跨平臺。簡單的說就是這段程式既可以在windows下,換到linux下也可以不加修改的執行起來,聽起來就不錯。所以,這個函式就可以派上用場了。
假設,我們想實現一個清除終端,linux下用clear, windows下用cls
Ostype=sys.platform()
If ostype==”linux” or ostype==”linux2”:
Cmd=”clear”
Else:
  Cmd=”cls”
(3) sys.exit(n)
執行至主程式的末尾時,直譯器會自動退出. 但是如果需要中途退出程式, 你可以呼叫sys.exit 函式, 它帶有一個可選的整數引數返回給呼叫它的程式. 這意味著你可以在主程式中捕獲對sys.exit 的呼叫。(注:0是正常退出,其他為不正常,可拋異常事件供捕獲!)
import sys
 
def exitfunc(value):
    '''Clear function'''
    print value
    sys.exit(0)
 
print "hello"
 
try:
    sys.exit(1)
except SystemExit,value:
    exitfunc(value)
 
print "come?"
輸出結果:
[
[email protected]
scripts]# python test.py
hello
1
以下是python.org庫參考手冊中,摘抄來的,供參考。
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level. The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to sys.stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.
 
大概意思是說,sys.exit從python程式中退出,將會產生一個systemExit異常,可以為此做些清除除理的工作。這個可選引數預設正常退出狀態是0,以數值為引數的範圍為:0-127。其他的數值為非正常退出,還有另一種型別,在這裡展現的是strings物件型別。
(4)sys.path
大家對模組都有一定了解吧?大家在使用模組的某一個功能前,是不是需要匯入呢?答案是需要。那import,__import__命令就不用提幹嘛的了吧。那大家在執行import module_name的時候,python內部發生了什麼呢?簡單的說,就是搜尋module_name。根據sys.path的路徑來搜尋module.name
>>> sys.path
['', '/usr/local/lib/python24.zip', '/usr/local/lib/python2.4', '/usr/local/lib/python2.4/plat-freebsd4', '/usr/local/lib/python2.4/lib-tk', '/usr/local/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages']
大家以後寫好的模組就可以放到上面的某一個目錄下,便可以正確搜尋到了。當然大家也可以新增自己的模組路徑。Sys.path.append(“mine module path”).
 
(5)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.
Python.org手冊裡已經說的很明白了。
For names in sys.modules.keys():
If names != ’sys’:
    ……
(6)sys.stdin,sys.stdout,sys.stderr
stdin , stdout , 以及stderr 變數包含與標準I/O 流對應的流物件. 如果需要更好地控制輸出,而print 不能滿足你的要求, 它們就是你所需要的. 你也可以替換它們, 這時候你就可以重定向輸出和輸入到其它裝置( device ), 或者以非標準的方式處理它們
從網上摘抄的文章,供大家參考:
#testing stdout


print 'Hello World!'
執行hello.py就會在標準輸出的螢幕上列印 Hello World!, 我們再編一個簡單的標準輸入的小程式 sayhi.py:
#testing stdin


print 'Hi, %s!' % raw_input('Please enter your name:')
當你用鍵盤輸入你的名字後,程式在螢幕上輸出Hi,[你的名字]!, 這就是從標準輸入:鍵盤獲取資訊,再輸出到標準輸出:螢幕的例子。
那麼上面的例子中print 和 raw_input是如何與標準輸入/輸出流建立關係的呢?
其實Python程式的標準輸入/輸出/出錯流定義在sys模組中,分別 為: sys.stdin, sys.stdout, sys.stderr
上面的程式分別與下列的程式是一樣的:
import sys


sys.stdout.write('Hello World!')
import sys


print 'Please enter your name:',
name=sys.stdin.readline()[:-1]
print 'Hi, %s!' % name


那麼sys.stdin, sys.stdout, stderr到底是什麼呢?我們在Python執行環境中輸入以下程式碼:
import sys
for f in (sys.stdin, sys.stdout, sys.stderr): print f
輸出為:
<open file '<stdin>', mode 'r' at 892210>
<open file '<stdout>', mode 'w' at 892270>
<open file '<stderr>', mode 'w at 8922d0>


由此可以看出stdin, stdout, stderr在Python中無非都是檔案屬性的物件,他們在Python啟動時自動與Shell 環境中的標準輸入,輸出,出錯關聯。
而Python程式的在Shell中的I/O重定向與本文開始時舉的DOS命令的重定向完全相同,其實這種重定向是由Shell來提供的,與Python 本身並無關係。那麼我們是否可以在Python程式內部將stdin,stdout,stderr讀寫操作重定向到一個內部物件呢?答案是肯定的。
Python提供了一個StringIO模組來完成這個設想,比如:
from StringIO import StringIO
import sys
buff =StringIO()


temp = sys.stdout                               #儲存標準I/O流
sys.stdout = buff                                 #將標準I/O流重定向到buff物件
print 42, 'hello', 0.001


sys.stdout =temp                                 #恢復標準I/O流
print buff.getvalue()