在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ Python/ 標準庫 (2)
標準庫 (4)
如何成為 Python 高手
標準庫 (6)
標準庫 (3)
類(2)
Pandas 使用 (2)
xml
用 tornado 做網(wǎng)站 (5)
文件(1)
練習
列表(3)
從小工到專家
除法
錯誤和異常 (2)
函數(shù)(1)
用 tornado 做網(wǎng)站 (7)
為做網(wǎng)站而準備
函數(shù)練習
標準庫 (8)
Pandas 使用 (1)
回顧 list 和 str
字典(1)
用 tornado 做網(wǎng)站 (3)
字符串(1)
函數(shù)(2)
寫一個簡單的程序
將數(shù)據(jù)存入文件
語句(5)
SQLite 數(shù)據(jù)庫
集成開發(fā)環(huán)境(IDE)
集合(1)
類(1)
用 tornado 做網(wǎng)站 (6)
用 tornado 做網(wǎng)站 (2)
自省
語句(4)
錯誤和異常 (1)
用 tornado 做網(wǎng)站 (4)
集合(2)
列表(1)
標準庫 (1)
生成器
mysql 數(shù)據(jù)庫 (1)
第三方庫
實戰(zhàn)
運算符
類(3)
字典(2)
語句(1)
數(shù)和四則運算
語句(2)
文件(2)
MySQL 數(shù)據(jù)庫 (2)
電子表格
迭代器
mongodb 數(shù)據(jù)庫 (1)
特殊方法 (2)
特殊方法 (1)
字符編碼
編寫模塊
用 tornado 做網(wǎng)站 (1)
標準庫 (5)
函數(shù)(4)
類(5)
字符串(2)
關于 Python 的故事
函數(shù)(3)
字符串(4)
處理股票數(shù)據(jù)
常用數(shù)學函數(shù)和運算優(yōu)先級
字符串(3)
為計算做準備
多態(tài)和封裝
類(4)
迭代
語句(3)
錯誤和異常 (3)
分析 Hello
Python 安裝
標準庫 (2)
列表(2)
元組

標準庫 (2)

Python 標準庫內(nèi)容非常多,有人專門為此寫過一本書。在本教程中,由于我的原因,不會將標準庫進行完整的詳細介紹,但是,我根據(jù)自己的理解和喜好,選幾個呈現(xiàn)出來,一來顯示標準庫之強大功能,二來演示如何理解和使用標準庫。

sys

這是一個跟 Python 解釋器關系密切的標準庫,上一節(jié)中我們使用過 sys.path.append()

>>> import sys
>>> print sys.__doc__

顯示了 sys 的基本文檔,看第一句話,概括了本模塊的基本特點。

This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

在諸多 sys 函數(shù)和變量中,選擇常用的(應該說是我覺得常用的)來說明。

sys.argv

sys.argv 是變量,專門用來向 Python 解釋器傳遞參數(shù),所以名曰“命令行參數(shù)”。

先解釋什么是命令行參數(shù)。

$ Python --version
Python 2.7.6

這里的--version 就是命令行參數(shù)。如果你使用 Python --help 可以看到更多:

$ Python --help
usage: Python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-B     : don't 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

只選擇了部分內(nèi)容擺在這里。所看到的如 -B, -h 之流,都是參數(shù),比如 Python -h,其功能同上。那么 -h 也是命令行參數(shù)。

sys.arg 在 Python 中的作用就是這樣。通過它可以向解釋器傳遞命令行參數(shù)。比如:

#!/usr/bin/env Python
# coding=utf-8

import sys

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

將上述代碼保存,文件名是 22101.py(這名稱取的,多么數(shù)字化)。然后如此做:

$ python 22101.py
The file name:  22101.py
The number of argument 1
The argument is:  ['22101.py']

將結果和前面的代碼做個對照。

  • $ Python 22101.py 中,“22101.py”是要運行的文件名,同時也是命令行參數(shù),是前面的Python 這個指令的參數(shù)。其地位與 Python -h 中的參數(shù) -h 是等同的。
  • sys.argv[0] 是第一個參數(shù),就是上面提到的 22101.py,即文件名。

如果我們這樣來試試,看看結果:

$ python 22101.py beginner master www.itdiffer.com
The file name:  22101.py
The number of argument 4
The argument is:  ['22101.py', 'beginner', 'master', 'www.itdiffer.com']

如果在這里,用 sys.arg[1] 得到的就是 beginner,依次類推。

sys.exit()

這是一個方法,意思是退出當前的程序。

Help on built-in function exit in module sys:

exit(...)
    exit([status])

    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is an integer, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).

從文檔信息中可知,如果用 sys.exit() 退出程序,會返回 SystemExit 異常。這里先告知讀者,還有另外一退出方式,是 os._exit(),這兩個有所區(qū)別。后者會在后面介紹。

#!/usr/bin/env Python
# coding=utf-8

import sys

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

這段程序的運行結果就是:

$ python 22102.py
0
1
2
3
4

需要提醒讀者注意的是,在函數(shù)中,用到 return,這個的含義是終止當前的函數(shù),并返回相應值(如果有,如果沒有就是 None)。但是 sys.exit() 的含義是退出當前程序,并發(fā)起 SystemExit 異常。這就是兩者的區(qū)別了。

如果使用 sys.exit(0) 表示正常退出。如果讀者要測試,需要在某個地方退出的時候有一個有意義的提示,可以用 sys.exit("I wet out at here."),那么字符串信息就被打印出來。

sys.path

sys.path 已經(jīng)不陌生了,前面用過。它可以查找模塊所在的目錄,以列表的形式顯示出來。如果用append() 方法,就能夠向這個列表增加新的模塊目錄。如前所演示。不在贅述。不理解的讀者可以往前復習。

sys.stdin, sys.stdout, sys.stderr

這三個放到一起,因為他們的變量都是類文件流對象,分別表示標準 UNIX 概念中的標準輸入、標準輸出和標準錯誤。與 Python 功能對照,sys.stdin 獲得輸入(用 raw_input() 輸入的通過它獲得,Python3.x 中是 imput()),sys.stdout 負責輸出了。

流是程序輸入或輸出的一個連續(xù)的字節(jié)序列,設備(例如鼠標、鍵盤、磁盤、屏幕、調(diào)制解調(diào)器和打印機)的輸入和輸出都是用流來處理的。程序在任何時候都可以使用它們。一般來講,stdin(輸入)并不一定來自鍵盤,stdout(輸出)也并不一定顯示在屏幕上,它們都可以重定向到磁盤文件或其它設備上。

還記得 print() 吧,在這個學習過程中,用的很多。它的本質(zhì)就是 sys.stdout.write(object + '\n')

>>> for i in range(3):
...     print i
... 
0
1
2

>>> import sys
>>> for i in range(3):
...     sys.stdout.write(str(i))
... 
012>>> 

造成上面輸出結果在表象上如此差異,原因就是那個'\n'的有無。

>>> for i in range(3):
...     sys.stdout.write(str(i) + '\n')
... 
0
1
2

從這看出,兩者是完全等效的。如果僅僅止于此,意義不大。關鍵是通過 sys.stdout 能夠做到將輸出內(nèi)容從“控制臺”轉(zhuǎn)到“文件”,稱之為重定向。這樣也許控制臺看不到(很多時候這個不重要),但是文件中已經(jīng)有了輸出內(nèi)容。比如:

>>> f = open("stdout.md", "w")
>>> sys.stdout = f
>>> print "Learn Python: From Beginner to Master"
>>> f.close()

sys.stdout = f 之后,就意味著將輸出目的地轉(zhuǎn)到了打開(建立)的文件中,如果使用 print(),即將內(nèi)容輸出到這個文件中,在控制臺并無顯現(xiàn)。

打開文件看看便知:

$ cat stdout.md
Learn Python: From Beginner to Master

這是標準輸出。另外兩個,輸入和錯誤,也類似。讀者可以自行測試。

關于對文件的操作,雖然前面這這里都涉及到一些。但是,遠遠不足,后面我會專門講授對某些特殊但常用的文件讀寫操作。

copy

《字典(2)》中曾經(jīng)對 copy 做了講授,這里再次提出,即是復習,又是湊數(shù),以顯得我考慮到了這個常用模塊,還有:

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

這個模塊中常用的就是 copy 和 deepcopy。

為了具體說明,看這樣一個例子:

#!/usr/bin/env Python
# coding=utf-8

import copy

class MyCopy(object):
    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 "original: %r\n slice: %r\n list(): %r\n copy(): %r\n deepcopy(): %r\n" % (a,b,c,d,e)

保存并運行:

$ python 22103.py 
original: ['foo', 17, 'abc']
 slice: ['foo', 17]
 list(): ['foo', 17]
 copy(): ['foo', 17]
 deepcopy(): ['foo', 7]

讀者可以對照結果和程序,就能理解各種拷貝的實現(xiàn)方法和含義了。


總目錄   |   上節(jié):標準庫(1)   |   下節(jié):標準庫(3)

如果你認為有必要打賞我,請通過支付寶:qiwsir@126.com,不勝感激。

上一篇:標準庫 (4)下一篇:迭代器