寫在之前

標準庫的內容非常多,有人專門為標準庫寫過一本書,在接下來的幾天我會根據我自己的理解,選幾個給大家學一下,一來是為了顯示一下標準庫的強大,二來演示如何理解和使用標準庫。

sys

sys 是常用的標準庫,相信已經不陌生了,這是一個跟 Python 解釋器關係密切的標準庫,前面已經使用過:sys.path.append()。

>>> import sys
>>> print(sys.__doc__)
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:

上面顯示了 sys 的基本文檔,第一句話概括了本模塊的基本特點。在諸多的 sys 函數和屬性中,我選幾個常用的來說明:

1.sys.argv

sys.argv 是專門用來向 Python 解釋器傳遞參數的,所以稱之為「命令行參數」,下面先解釋一下什麼是命令行參數:

$ python3 --version

Python 3.6.5

這裡的 --version 就是命令行參數,如果使用 Python -help 的,則可以看到更多:

python --help

usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...

Options and arguments (and corresponding environment variables):

-b : issue warnings about comparing bytearray with unicode

(-bb: issue errors)

-B : dont write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x

-c cmd : program passed in as string (terminates option list)

-d : debug output from parser; also PYTHONDEBUG=x

-E : ignore PYTHON* environment variables (such as PYTHONPATH)

-h : print this help message and exit (also --help)

-i : inspect interactively after running script; forces a prompt even

if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-m mod : run library module as a script (terminates option list)

-O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x

-OO : remove doc-strings in addition to the -O optimizations

-R : use a pseudo-random salt to make hash() values of various types be

unpredictable between separate invocations of the interpreter, as

a defense against denial-of-service attacks

上面只是顯示了一部分內容,你所看到的 -B,-h 都是參數,比如 python -h,其功能同上,所以 -h 也是命令行參數。

sys.arg 的作用就是通過它向解釋器傳遞命令行參數,比如下面這個例子:

import sys

print(the file name:,sys.argv[0])
print(the number of argument,len(sys.argv))
print(the augument is:,str(sys.argv))

將上述代碼保存,文件名是 test.py,然後做下述操作:

$ python sys_file.py
the file name: test.py
the number of argument 1
the augument is: [test.py]

將結果與前面的代碼做個對比,在 $python sys_file.py 中,sys_file.py 是要運行的文件名,同時也是命令行參數,是前面的 Python 這個指令的參數,其地位與 Python -h 中的參數 -h 是等同的。再者就是,sys.argv[0] 是第一個參數,就是上面提到的 sys_file.py,即文件名。

2.sys.exit()

這個方法的作用是退出當前程序,我們下面來看一個例子:

import sys

for i in range(10):
if i == 5:
sys.exit()
else:
print(i)

上面這段程序的運行結果如下:

0
1
2
3
4

在大多數函數中會用到 return,其含義是中止當前的函數,並向調用函數的位置返回相應值(如果沒有就返回 None)。但是 sys.exit() 的含義是退出當前程序(不僅僅是退出當前函數),並發起 SystemExit 異常,這就是兩者的區別。

如果使用 sys.exit(0) 表示正常退出,則需要在退出的時候有一個對人友好的提示,可以用 sys.exit(「I wet out at here.」),那麼字元串信息就會被列印出來。

3.sys.path

sys.path 已經不陌生了,它可以查找模塊所在的目錄,以列表的形式表示出來。如果用 append() 方法,就能夠向這個列表增加新的模塊目錄,就像前面所演示的那樣,在這就不再贅述了。

copy

我們在很久以前對淺拷貝和深拷貝做了研究,這裡再次提出,做到溫故而知新。

>>> import copy
>>> copy.__all__
[Error, copy, deepcopy]

這個模塊中常用的就是 copy 和 deepcopy。為了具體說明,請看下面這個例子,這個例子和以前討論淺拷貝和深拷貝時略有不同,請大家認真推敲結果,並且對照代碼:

import copy

class Mycopy:
def __init__(self,value):
self.value = value

def __repr__(self):
return str(self.value)

foo = Mycopy(7)

a = [foo,foo]
b = a[:]
c = list(a)
d = copy.copy(a)
e = copy.deepcopy(a)

a.append(abc)
foo.value = 17

print("oriangle:{0}
slice:{1}
list():{2}
copy():{3}
deepcopy():{4}
".format(a,b,c,d,e))

把上述結果保存並且運行得到下面得結果:

oriangle:[foo, 17, abc]
slice:[foo, 17]
list():[foo, 17]
copy():[foo, 17]
deepcopy():[foo, 7]

仔細看上面得結果,一切盡在不言中,請大家仔細對照上面顯示得結果,體會深拷貝和淺拷貝得實現方法和含義。

寫在之後

更多內容,歡迎關注公眾號「Python空間」,期待和你的交流。


推薦閱讀:
相關文章