老程式員快速掌握一門新的語言,如果還是逐個看文法手冊,太費時間了,通過一篇文章,無需太多解析,自己就可以看個大概了。接下來看看标準庫,然後就可以開始幹活了。
先來看一個簡單的任務:
簡單測試區域網路中的電腦是否連通.這些電腦的ip範圍從..到...
import subprocess
cmd="cmd.exe"
begin=
end=
while begin<end:
p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
p.stdin.write("ping 192.168.1."+str(begin)+"\n")
p.stdin.close()
p.wait()
print "execution result: %s"%p.stdout.read()
這個程式儲存之後可以直接運作.
快速入門
Hello world
安裝完Python之後,打開IDLE(Python GUI) , 該程式是Python語言解釋器,你寫的語句能夠立即運作.我們寫下一句著名的程式語句:
print "Hello,world!"
并按回車.你就能看到這句被K&R引入到程式世界的名言.
在解釋器中選擇"File"--"New Window" 或快捷鍵 Ctrl+N , 打開一個新的編輯器.寫下如下語句:
print "Hello,world!"
raw_input("Press enter key to close this window");
儲存為a.py檔案.按F5,你就可以看到程式的運作結果了.這是Python的第二種運作方式.
找到你儲存的a.py檔案,輕按兩下.也可以看到程式結果.Python的程式能夠直接運作.
國際化支援
我們換一種方式來問候世界.建立一個編輯器并寫如下代碼:
print "歡迎來到奧運中國!"
raw_input("Press enter key to close this window");
在你儲存代碼的時候,Python會提示你是否改變檔案的字元集,結果如下:
# -*- coding: cp936 -*-
print "歡迎來到奧運中國!"
raw_input("Press enter key to close this window");
将該字元集改為我們更熟悉的形式:
# -*- coding: GBK -*-
print "歡迎來到奧運中國!" # 使用中文的例子
raw_input("Press enter key to close this window");
程式一樣運作良好.
友善易用的電腦
用微軟附帶的電腦來計數實在太麻煩了.打開Python解釋器,直接進行計算:
a=
b=
c=
print (a+b+c)/c
字元串,ASCII和UNICODE
可以如下列印出預定義輸出格式的字元串:
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
字元串是怎麼通路的?請看這個例子:
word="abcdefg"
a=word[]
print "a is: "+a
b=word[:]
print "b is: "+b # index 1 and 2 elements of word.
c=word[:]
print "c is: "+c # index 0 and 1 elements of word.
d=word[:]
print "d is: "+d # All elements of word.
e=word[:]+word[:]
print "e is: "+e # All elements of word.
f=word[-]
print "f is: "+f # The last elements of word.
g=word[-:-]
print "g is: "+g # index 3 and 4 elements of word.
h=word[-:]
print "h is: "+h # The last two elements.
i=word[:-]
print "i is: "+i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
請注意ASCII和UNICODE字元串的差別:
print "Input your Chinese name:"
s=raw_input("Press enter to be continued");
print "Your name is : " +s;
l=len(s)
print "Length of your Chinese name in asc codes is:"+str(l);
a=unicode(s,"GBK")
l=len(a)
print "I'm sorry we should use unicode char!Characters number of your Chinese \
name in unicode is:"+str(l);
使用List
類似Java裡的List,這是一種友善易用的資料類型:
word=['a','b','c','d','e','f','g']
a=word[]
print "a is: "+a
b=word[:]
print "b is: "
print b # index 1 and 2 elements of word.
c=word[:]
print "c is: "
print c # index 0 and 1 elements of word.
d=word[:]
print "d is: "
print d # All elements of word.
e=word[:]+word[:]
print "e is: "
print e # All elements of word.
f=word[-]
print "f is: "
print f # The last elements of word.
g=word[-:-]
print "g is: "
print g # index 3 and 4 elements of word.
h=word[-:]
print "h is: "
print h # The last two elements.
i=word[:-]
print "i is: "
print i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
print "Adds new element"
word.append('h')
print word
條件和循環語句
# Multi-way decision
x=int(raw_input("Please enter an integer:"))
if x<:
x=
print "Negative changed to zero"
elif x==:
print "Zero"
else:
print "More"
# Loops List
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
如何定義函數
# Define and invoke function.
def sum(a,b):
return a+b
func = sum
r = func(,)
print r
# Defines function with default argument
def add(a,b=):
return a+b
r=add()
print r
r=add(,)
print r
并且,介紹一個友善好用的函數:
# The range() function
a =range(,)
print a
a = range(-,-)
print a
a = range(-,-)
print a
a = range(-,-,-) # The 3rd parameter stands for step
print a
檔案I/O
spath="D:/download/baa.txt"
f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist.
f.write("First line 1.\n")
f.writelines("First line 2.")
f.close()
f=open(spath,"r") # Opens file for reading
for line in f:
print line
f.close()
異常處理
s=raw_input("Input your age:")
if s =="":
raise Exception("Input must no be empty.")
try:
i=int(s)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unknown exception!"
else: # It is useful for code that must be executed if the try clause does not raise an exception
print "You are %d" % i," years old"
finally: # Clean up action
print "Goodbye!"
類和繼承
class Base:
def __init_(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
# Child extends Base
class Child(Base):
def plus(self,a,b):
return a+b
oChild =Child()
oChild.add("str1")
print oChild.data
print oChild.plus(,)
包機制
每一個.py檔案稱為一個module,module之間可以互相導入.請參看以下例子:
# a.py
def add_func(a,b):
return a+b
# b.py
from a import add_func # Also can be : import a
print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(,) # If using "import a" , then here should be "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的包路徑.你可以将之列印出來:
import sys
print sys.path
通常我們可以将module的包路徑放到環境變量PYTHONPATH中,該環境變量會自動添加到sys.path屬性.另一種友善的方法是程式設計中直接指定我們的module路徑到sys.path 中:
import sys
sys.path.append('D:\\download')
from parent.child.a import add_func
print sys.path
print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(,)