【補充教材】

中文python教學文件
http://www.freebsd.org.hk/html/python/tut_tw/tut.html


【實作練習:剖析 /etc/passwd 中的 UID】


#!/usr/bin/python

password_file = open('/etc/passwd')
#預設不加參數時,open 的參數即為 r (=read)

for i in password_file:
    if int(i.split(':')[2]) >= 500:
        print i.split(':')[0], i.split(':')[2]
    #也可以用多重賦值 (Multiple Assignment) 的方式
    #acc, uid = i.split(':')[0], i.split(':')[2]

password_file.close()



【實作練習:如何寫成一個模組】

1. 介紹如何撰寫函式:簡單的函式範例
#!/usr/bin/python

def hello():
        print "Hello world"
#函式 hello() 定義為印出字串 Hello world

hello()
#執行函式 hello()


2. 修改上述的函式:增加傳入值
#!/usr/bin/python

def hello(name="unkown"):
        print "Hello " + name
#重新設計 hello() 函式,使之有傳入值 name
#預設在未傳入任何值的情況下,name = "unkown"

hello()
#不傳入任何值,印出 "Hello unkown"
hello("willie")
#傳入willie,印出 "Hello willie"



3.傳入多重參數

#!/usr/bin/python



def hello(name, email="abc@com"):

        print "Hello " + name

#無預設值的值必須在有預設值的之前
#若設為 def hello(name="unkown", email),會出現錯誤


hello()

#未傳入任何值,會有錯誤

hello("willie")

#傳入willie,因此name="willie",email="abc@com"




4.修改前面的剖析:
先在 vi 中,command 模式下按大寫 V (按上下鍵可選取一段程式碼)
再按下 > (按下大於鍵後,剛才選取的程式碼就會整個向內縮排)

接著將剛才寫的剖析程式包成模組(檔名存成 tools.py):
(以下的程式碼是我的版本,不是 willie 的版本)
#!/usr/bin/python
#-*- coding: utf-8 -*-
def finduser():
        "This function is used to find out the normal user account."
        import os
        f = open('/etc/passwd', 'r')
        for i in f:
            name = i.split(':')[0]
            acc = i.split(':')[2]
            if int(acc) > 500:
                if len(name) > 7:
                        print name + '\t'*2 + acc
                else:
                        print name + '\t'*3 + acc
        f.close()


進入 python 的 command line 模式(在 command 輸入 python 按 enter),
  import tools  #匯入剛才寫好的模組
  dir(tools)   #可以檢視 tools 下有哪些方法可使用
  help(tools.finduser)  #可看到 def 下一行雙引號中撰寫的說明
  tools.finduser()    #執行後即可印出 /etc/password 中剛才剖析出的內容

備註:
#-*- coding: utf-8 -*-   ←表示使用 utf-8 編碼
#-*- coding: cp950 -*-   ←表示使用 Big5 編碼(windows 下使用)

若未加上上述的宣告,在程式中寫入中文註解會導致錯誤產生
arrow
arrow
    全站熱搜

    小攻城師 發表在 痞客邦 留言(0) 人氣()