本文適合有經驗的程序員盡快進入Python世界.特別地,如果你掌握Java和Javascript,不用1小時你就可以用Python快速流暢地寫有用的Python程序.
假設我們有這么一項任務:簡單測試局域網中的電腦是否連通.這些電腦的ip范圍從192.168.0.101到192.168.0.200.
思路:用shell編程.(Linux通常是bash而Windows是批處理腳本).例如,在Windows上用ping ip 的命令依次測試各個機器并得到控制臺輸出.由于ping通的時候控制臺文本通常是"Reply from ... " 而不通的時候文本是"time out ... " ,所以,在結果中進行字符串查找,即可知道該機器是否連通.
實現:Java代碼如下:
Stringcmd="cmd.exeping";
Stringipprefix="192.168.10.";
intbegin=101;
intend=200;
Processp=null;
for(inti=begin;i
p=Runtime.getRuntime().exec(cmd+i);
Stringline=null;
BufferedReaderreader=newBufferedReader(newInputStreamReader(p.getInputStream()));
while((line=reader.readLine())!=null)
{
//Handlingline,maylogsit.
}
reader.close();
p.destroy();
}
這段代碼運行得很好,問題是為了運行這段代碼,你還需要做一些額外的工作.這些額外的工作包括:
編寫一個類文件
編寫一個main方法
將之編譯成字節代碼
由于字節代碼不能直接運行,你需要再寫個小小的bat或者bash腳本來運行.
當然,用C/C++同樣能完成這項工作.但C/C++不是跨平臺語言.在這個足夠簡單的例子中也許看不出C/C++和Java實現的區別,但在一些更為復雜的場景,比如要將連通與否的信息記錄到網絡數據庫.由于Linux和Windows的網絡接口實現方式不同,你不得不寫兩個函數的版本.用Java就沒有這樣的顧慮.
同樣的工作用Python實現如下:
importsubprocess
cmd="cmd.exe"
begin=101
end=200
whilebegin
p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
p.stdin.write("ping192.168.1."+str(begin)+"/n")
p.stdin.close()
p.wait()
print"executionresult:%s"%p.stdout.read()
對比Java,Python的實現更為簡潔,你編寫的時間更快.你不需要寫main函數,并且這個程序保存之后可以直接運行.另外,和Java一樣,Python也是跨平臺的.
有經驗的C/Java程序員可能會爭論說用C/Java寫會比Python寫得快.這個觀點見仁見智.我的想法是當你同時掌握Java和Python之后,你會發現用Python寫這類程序的速度會比Java快上許多.例如操作本地文件時你僅需要一行代碼而不需要Java的許多流包裝類.各種語言有其天然的適合的應用范圍.用Python處理一些簡短程序類似與操作系統的交互編程工作最省時省力.
足夠簡單的任務,例如一些shell編程.如果你喜歡用Python設計大型商業網站或者設計復雜的游戲,悉聽尊便.
2 快速入門
安裝完Python之后(我本機的版本是2.5.4),打開IDLE(Python GUI) , 該程序是Python語言解釋器,你寫的語句能夠立即運行.我們寫下一句著名的程序語句:
print"Hello,world!"
并按回車.你就能看到這句被K&R引入到程序世界的名言.
在解釋器中選擇"File"--"New Window" 或快捷鍵 Ctrl+N , 打開一個新的編輯器.寫下如下語句:
print"Hello,world!"
raw_input("Pressenterkeytoclosethiswindow");
保存為a.py文件.按F5,你就可以看到程序的運行結果了.這是Python的第二種運行方式.
找到你保存的a.py文件,雙擊.也可以看到程序結果.Python的程序能夠直接運行,對比Java,這是一個優勢.
我們換一種方式來問候世界.新建一個編輯器并寫如下代碼:
print"歡迎來到奧運中國!"
raw_input("Pressenterkeytoclosethiswindow");
在你保存代碼的時候,Python會提示你是否改變文件的字符集,結果如下:
# -*- coding: cp936 -*-
print"歡迎來到奧運中國!"
raw_input("Pressenterkeytoclosethiswindow");
將該字符集改為我們更熟悉的形式:
# -*- coding: GBK -*-
print"歡迎來到奧運中國!" # 使用中文的例子
raw_input("Pressenterkeytoclosethiswindow");
程序一樣運行良好.
用微軟附帶的計算器來計數實在太麻煩了.打開Python解釋器,直接進行計算:
a=100.0
b=201.1
c=2343
print(a+b+c)/c
可以如下打印出預定義輸出格式的字符串:
print"""
Usage:thingy[OPTIONS]
-hDisplaythisusagemessage
-HhostnameHostnametoconnectto
"""
字符串是怎么訪問的?請看這個例子:
word="abcdefg"
a=word[2]
print"ais:"+a
b=word[1:3]
print"bis:"+b#index1and2elementsofword.
c=word[:2]
print"cis:"+c#index0and1elementsofword.
d=word[0:]
print"dis:"+d#Allelementsofword.
e=word[:2]+word[2:]
print"eis:"+e#Allelementsofword.
f=word[-1]
print"fis:"+f#Thelastelementsofword.
g=word[-4:-2]
print"gis:"+g#index3and4elementsofword.
h=word[-2:]
print"his:"+h#Thelasttwoelements.
i=word[:-2]
print"iis:"+i#Everythingexceptthelasttwocharacters
l=len(word)
print"Lengthofwordis:"+str(l)
請注意ASCII和UNICODE字符串的區別:
print"InputyourChinesename:"
s=raw_input("Pressentertobecontinued");
print"Yournameis:"+s;
l=len(s)
print"LengthofyourChinesenameinasccodesis:"+str(l);
a=unicode(s,"GBK")
l=len(a)
print"I'msorryweshoulduseunicodechar!CharactersnumberofyourChinese/
nameinunicodeis:"+str(l);
類似Java里的List,這是一種方便易用的數據類型:
word=['a','b','c','d','e','f','g']
a=word[2]
print"ais:"+a
b=word[1:3]
print"bis:"
printb#index1and2elementsofword.
c=word[:2]
print"cis:"
printc#index0and1elementsofword.
d=word[0:]
print"dis:"
printd#Allelementsofword.
e=word[:2]+word[2:]
print"eis:"
printe#Allelementsofword.
f=word[-1]
print"fis:"
printf#Thelastelementsofword.
g=word[-4:-2]
print"gis:"
printg#index3and4elementsofword.
h=word[-2:]
print"his:"
printh#Thelasttwoelements.
i=word[:-2]
print"iis:"
printi#Everythingexceptthelasttwocharacters
l=len(word)
print"Lengthofwordis:"+str(l)
print"Addsnewelement"
word.append('h')
printword
#Multi-waydecision
x=int(raw_input("Pleaseenteraninteger:"))
ifx<0:
x=0
print"Negativechangedtozero"
elifx==0:
print"Zero"
else:
print"More"
#LoopsList
a=['cat','window','defenestrate']
forxina:
printx,len(x)
#Defineandinvokefunction.
defsum(a,b):
returna+b
func=sum
r=func(5,6)
printr
#Definesfunctionwithdefaultargument
defadd(a,b=2):
returna+b
r=add(1)
printr
r=add(1,5)
printr
并且,介紹一個方便好用的函數:
#Therange()function
a=range(5,10)
printa
a=range(-2,-7)
printa
a=range(-7,-2)
printa
a=range(-2,-11,-3)#The3rdparameterstandsforstep
printa
spath="D:/download/baa.txt"
f=open(spath,"w")#Opensfileforwriting.Createsthisfiledoesn'texist.
f.write("Firstline1./n")
f.writelines("Firstline2.")
f.close()
f=open(spath,"r")#Opensfileforreading
forlineinf:
printline
f.close()
s=raw_input("Inputyourage:")
ifs=="":
raiseException("Inputmustnobeempty.")
try:
i=int(s)
exceptValueError:
print"Couldnotconvertdatatoaninteger."
except:
print"Unknownexception!"
else:#Itisusefulforcodethatmustbeexecutedifthetryclausedoesnotraiseanexception
print"Youare%d"%i,"yearsold"
finally:#Cleanupaction
print"Goodbye!"
classBase:
def__init__(self):
self.data=[]
defadd(self,x):
self.data.append(x)
defaddtwice(self,x):
self.add(x)
self.add(x)
#ChildextendsBase
classChild(Base):
defplus(self,a,b):
returna+b
oChild=Child()
oChild.add("str1")
printoChild.data
printoChild.plus(2,3)
每一個.py文件稱為一個module,module之間可以互相導入.請參看以下例子:
#a.py
defadd_func(a,b):
returna+b
#b.py
fromaimportadd_func#Alsocanbe:importa
print"Importadd_funcfrommodulea"
print"Resultof1plus2is:"
printadd_func(1,2)#Ifusing"importa",thenhereshouldbe"a.add_func"
module可以定義在包里面.Python定義包的方式稍微有點古怪,假設我們有一個parent文件夾,該文件夾有一個child子文件夾.child中有一個module a.py . 如何讓Python知道這個文件層次結構?很簡單,每個目錄都放一個名為_init_.py 的文件.該文件內容可以為空.這個層次結構如下所示:
parent
--__init_.py
--child
--__init_.py
--a.py
b.py
那么Python如何找到我們定義的module?在標準包sys中,path屬性記錄了Python的包路徑.你可以將之打印出來:
importsys
printsys.path
通常我們可以將module的包路徑放到環境變量PYTHONPATH中,該環境變量會自動添加到sys.path屬性.另一種方便的方法是編程中直接指定我們的module路徑到sys.path 中:
importsys
sys.path.append('D://download')
fromparent.child.aimportadd_func
printsys.path
print"Importadd_funcfrommodulea"
print"Resultof1plus2is:"
printadd_func(1,2)
總結
你會發現這個教程相當的簡單.許多Python特性在代碼中以隱含方式提出,這些特性包括:Python不需要顯式聲明數據類型,關鍵字說明,字符串函數的解釋等等.我認為一個熟練的程序員應該對這些概念相當了解,這樣在你擠出寶貴的一小時閱讀這篇短短的教程之后,你能夠通過已有知識的遷移類比盡快熟悉Python,然后盡快能用它開始編程.
當然,1小時學會Python頗有嘩眾取寵之嫌.確切的說,編程語言包括語法和標準庫.語法相當于武術招式,而標準庫應用實踐經驗則類似于內功,需要長期鍛煉.Python學習了Java的長處,提供了大量極方便易用的標準庫供程序員"拿來主義".(這也是Python成功的原因),在開篇我們看到了Python如何調用Windows cmd的例子,以后我會盡量寫上各標準庫的用法和一些應用技巧,讓大家真正掌握Python.
但不管怎樣,至少你現在會用Python代替繁瑣的批處理寫程序了.希望那些真的能在一小時內讀完本文并開始使用Python的程序員會喜歡這篇小文章,謝謝!
新聞熱點
疑難解答