python之基礎篇(十)——執行環境與
- 2020 年 1 月 6 日
- 筆記
解釋器環境與選項
python解釋器啟動:
python [options] [-c cmd | filename | - ] [args]
選項 |
描述 |
---|---|
-3 |
啟用將從python3中刪除或更改某些功能的警告 |
-B |
阻止在導入時創建.pyc或.pyo文件 |
-E |
忽略環境變數 |
-h |
列印所有可用命令行選項的列表 |
-i |
在程式執行後進入交互模式 |
-m module |
以腳本的形式運行庫模組module |
-O |
優化模式 |
-OO |
優化模式,在創建.pyo文件時刪除文檔字元串 |
-Q arg |
指定python2中除法運算符的行為,值為-Qold(默認值)、-Qnew、-Qwarn或-Qwarnall之一 |
-s |
阻止將用戶站點目錄添加到sys.path |
-S |
阻止包含site初始化模組 |
-t |
報告關於不一致的標籤使用警告 |
-tt |
由於不一致的標籤使用而導致TabError異常 |
-u |
未緩衝的二進位stdout和stdin |
-U |
Unicode字面量。所有字元串字面量都以Unicode形式處理(僅在python2中使用) |
-v |
詳細模式。跟蹤導入語句 |
-V |
列印版本號並退出 |
-x |
跳過源程式的第一行 |
-c cmd |
以字元串形式執行cmd |
python解釋器環境變數:
環境變數 |
描述 |
---|---|
PYTHONPATH |
以冒號分隔的模組搜索路徑 |
PYTHONSTARTUP |
在以交互方式啟動時執行的文件 |
PYTHONHOME |
python安裝的位置 |
PYTHONINSPECT |
相當於-i選項 |
PYTHONUNBUFFERED |
相當於-u選項 |
PYTHONIOENCODING |
針對stdin、stdout和stderr的編碼和錯誤處理。這是一個encoding[:errors]形式的字元串,如utf-8或utf-8:ignore |
PYTHONDONIWRITEBYTECODE |
相當於-B選項 |
PYTHONOPTIMIZE |
相當於-O選項 |
PYTHONNOUSERSITE |
相當於-s選項 |
PYTHONVERBOSE |
相當於-v選項 |
PYTHONUSERBASE |
每個用戶站點包的根目錄 |
PYTHONCASEOK |
指示為導入所使用的模組名稱使用不區分大小寫的匹配方式 |
python程式碼的測試、調試與探查
基於文檔字元串來進行測試。
如果函數、類或模組的第一行是一個字元串,這個字元串就稱為文檔字元串(docstrings)。
內置函數help()或對象的默認方法__doc__可以顯示這些文檔字元串。
In [1]: def Sum(num1,num2): ...: '''The sumary of num1 and num2. ...: >>> Sum(2,5) ...: 7 ...: >>> Sum(12,77) ...: 89 ...: ''' ...: return num1 + num2 ...: In [2]: help(Sum) In [3]: Sum.__doc__ Out[3]: 'The sumary of num1 and num2.n >>> Sum(2,5)n 7n >>> Sum(12,77)n 89n '
doctest模組:
doctest模組允許在文檔字元串內嵌入注釋以顯示各種語句的期望行為,尤其是函數和方法的結果
此處的文檔字元串看起來如同一個互動式shell會話;
可用於測試文檔是否與程式主體保持同步,或基於文檔對程式本身做測試
自定義模組mymod:
[root@localhost test]# pwd /root/test [root@localhost test]# cat mymod.py #!/usr/bin/python def add(num1,num2): ''' >>> add(12,43) 55 ''' return num1 + num2
在互動式模式下使用doctest模組進行測試:
In [4]: import sys In [5]: sys.path.append('/root/test') #將/root/test加入模組搜索路徑 In [6]: import mymod In [7]: import doctest In [8]: doctest.testmod(mymod) Out[8]: TestResults(failed=0, attempted=1) In [9]: doctest.testmod(mymod,verbose=True) Trying: add(12,43) Expecting: 55 ok 1 items had no tests: mymod 1 items passed all tests: 1 tests in mymod.add 1 tests in 2 items. 1 passed and 0 failed. Test passed. Out[9]: TestResults(failed=0, attempted=1)
如果文檔字元串中的結果與預期結果不一致,測試會顯示出錯的結果資訊。
創建可自測試的模組:
在模組的尾部添加如下程式碼即可
[root@localhost test]# cat mymod.py #!/usr/bin/python def add(num1,num2): ''' >>> add(12,43) 55 ''' return num1 + num2 if __name__ == '__main__': import doctest print doctest.testmod(verbose=True) [root@localhost test]# python mymod.py Trying: add(12,43) Expecting: 55 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.add 1 tests in 2 items. 1 passed and 0 failed. Test passed. TestResults(failed=0, attempted=1)
此類模組在python解釋器中直接運行時即能進行自我測試。