|
#!/usr/bin/env python3 #第1行注釋可以讓這個(gè)hello.py文件直接在Unix/Linux/Mac上運(yùn)行 # -*- coding: utf-8 -*- #表示.py文件本身使用標(biāo)準(zhǔn)UTF-8編碼 ' a test module ' #是一個(gè)字符串,表示模塊的文檔注釋,任何模塊代碼的第一個(gè)字符串都被視為模塊的文檔注釋 __author__ = 'Michael Liao' #使用__author__變量把作者寫進(jìn)去,這樣當(dāng)你公開源代碼后別人就可以瞻仰你的大名 import sys #導(dǎo)入該sys模塊 #變量sys指向該模塊,利用sys這個(gè)變量,就可以訪問sys模塊的所有功能 def test(): args = sys.argv if len(args)==1: print('Hello, world!') elif len(args)==2: print('Hello, %s!' % args[1]) else: print('Too many arguments!') if __name__=='__main__': #標(biāo)準(zhǔn)測試 給命令行鋪墊 test() ----------------------------------------------------------------------- sys模塊有一個(gè)argv變量,用list存儲(chǔ)了命令行的所有參數(shù)。argv至少有一個(gè)元素, 因?yàn)榈谝粋€(gè)參數(shù)永遠(yuǎn)是該.py文件的名稱,例如: 運(yùn)行python3 hello.py獲得的sys.argv就是['hello.py']; 運(yùn)行python3 hello.py Michael獲得的sys.argv就是['hello.py', 'Michael]。 $ python3 hello.py Hello, world! $ python hello.py Michael Hello, Michael! 啟動(dòng)Python交互環(huán)境,再導(dǎo)入hello模塊: $ python3 Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import hello >>>hello.test() Hello, world! 當(dāng)我們在命令行運(yùn)行hello模塊文件時(shí),Python解釋器把一個(gè)特殊變量__name__置為__main__,而如果在其他地方導(dǎo)入該hello模塊時(shí),if判斷將失敗,因此, 這種if測試可以讓一個(gè)模塊通過命令行運(yùn)行時(shí)執(zhí)行一些額外的代碼,最常見的就是運(yùn)行測試。 分享知識(shí),分享快樂!希望中國站在編程之巔!
360圖書館館號(hào):rsgz002.360doc.com |
|
|