1. 程式人生 > >python的sys模塊

python的sys模塊

pretty ubunt exe 編碼 AS readline set 環境 添加

轉自:https://blog.csdn.net/zyc_love_study/article/details/78983817

python版本: Python 2.7.6
1: sys是python自帶模塊.
利用 import 語句輸入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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

(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‘
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

運行結果:

$ 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‘]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

(2) sys.exit

 #!/usr/bin/python
import sys

def exitfunc(value):
    print (value)
    sys.exit(0)

print("hello")

try:
    sys.exit(90)
except SystemExit as value:
    exitfunc(value)   

print("come?")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

運行結果:

hello
90
  • 1
  • 2

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

(3) sys.modules
sys.modules.keys() 返回所有已經導入的模塊列表
keys是模塊名
values是模塊
modules返回路徑

 #!/usr/bin/python
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 ‘copy_reg‘ from ‘/usr/lib/python2.7/copy_reg.pyc‘>, <module ‘sre_compile‘ from ‘/usr/lib/python2.7/sre_compile.pyc‘>, <module ‘_sre‘ (built-in)>, <module ‘encodings‘ from ‘/usr/lib/python2.7/encodings/__init__.pyc‘>, <module ‘site‘ from ‘/usr/lib/python2.7/site.pyc‘>, <module ‘__builtin__‘ (built-in)>, <module ‘sysconfig‘ from ‘/usr/lib/python2.7/sysconfig.pyc‘>, <module ‘__main__‘ from ‘sys-test1.py‘>, None, <module ‘abc‘ from ‘/usr/lib/python2.7/abc.pyc‘>, <module ‘posixpath‘ from ‘/usr/lib/python2.7/posixpath.pyc‘>, <module ‘_weakrefset‘ from ‘/usr/lib/python2.7/_weakrefset.pyc‘>, <module ‘errno‘ (built-in)>, None, <module ‘sre_constants‘ from ‘/usr/lib/python2.7/sre_constants.pyc‘>, <module ‘re‘ from ‘/usr/lib/python2.7/re.pyc‘>, <module ‘_abcoll‘ from ‘/usr/lib/python2.7/_abcoll.pyc‘>, <module ‘types‘ from ‘/usr/lib/python2.7/types.pyc‘>, <module ‘_codecs‘ (built-in)>, None, <module ‘_warnings‘ (built-in)>, <module ‘genericpath‘ from ‘/usr/lib/python2.7/genericpath.pyc‘>, <module ‘stat‘ from ‘/usr/lib/python2.7/stat.pyc‘>, <module ‘zipimport‘ (built-in)>, <module ‘_sysconfigdata‘ from ‘/usr/lib/python2.7/_sysconfigdata.pyc‘>, <module ‘warnings‘ from ‘/usr/lib/python2.7/warnings.pyc‘>, <module ‘UserDict‘ from ‘/usr/lib/python2.7/UserDict.pyc‘>, <module ‘encodings.ascii‘ from ‘/usr/lib/python2.7/encodings/ascii.pyc‘>, <module ‘sys‘ (built-in)>, <module ‘codecs‘ from ‘/usr/lib/python2.7/codecs.pyc‘>, <module ‘_sysconfigdata_nd‘ from ‘/usr/lib/python2.7/plat-x86_64-linux-gnu/_sysconfigdata_nd.pyc‘>, <module ‘posixpath‘ from ‘/usr/lib/python2.7/posixpath.pyc‘>, <module ‘sitecustomize‘ from ‘/usr/lib/python2.7/sitecustomize.pyc‘>, <module ‘signal‘ (built-in)>, <module ‘traceback‘ from ‘/usr/lib/python2.7/traceback.pyc‘>, <module ‘linecache‘ from ‘/usr/lib/python2.7/linecache.pyc‘>, <module ‘posix‘ (built-in)>, <module ‘encodings.aliases‘ from ‘/usr/lib/python2.7/encodings/aliases.pyc‘>, <module ‘exceptions‘ (built-in)>, <module ‘sre_parse‘ from ‘/usr/lib/python2.7/sre_parse.pyc‘>, <module ‘os‘ from ‘/usr/lib/python2.7/os.pyc‘>, <module ‘_weakref‘ (built-in)>]
*******************************************************************************
<module ‘os‘ from ‘/usr/lib/python2.7/os.pyc‘>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

(4) sys.stdin/sys.stdout/sys.stderr
stdin,stdout,stderr在Python中都是文件屬性對象, 他們在python啟動時自動與shell環境中的標準輸入, 輸出, 出錯相關. 而python程序在shell中的I/O重定向是有shell來提供的,與python本身沒有關系.python程序內部將stdin, stdout, stderr讀寫操作重定向到一個內部對象.

標準輸入
#!/usr/bin/python
import sys
#print(‘Hi, %s!‘ %input(‘Please enter your name: ‘)) python3.*版本用input
print(‘Hi, %s!‘ %raw_input(‘Please enter your name: ‘)) #python2.*版本用raw_input
運行結果:
Please enter your name: er
Hi, er!
等同於:
 #!/usr/bin/python
import sys
print(‘Please enter your name:‘)
name=sys.stdin.readline()[:-1]
print(‘Hi, %s!‘ %name)
標準輸出
print(‘Hello World!\n‘)
等同於:
 #!/usr/bin/python
import sys
sys.stdout.write(‘output resule is good!\n‘)
其他實驗
#!/usr/bin/python
import sys

for i in (sys.stdin, sys.stdout, sys.stderr):
    print(i)
執行結果:
python sys-test1.py
<open file ‘<stdin>‘, mode ‘r‘ at 0x7fa4e630f0c0>
<open file ‘<stdout>‘, mode ‘w‘ at 0x7fa4e630f150>
<open file ‘<stderr>‘, mode ‘w‘ at 0x7fa4e630f1e0>

python的sys模塊