Python的世界

可愛的Python——足夠簡單問題的解決之道


假設我們有這麼一項任務:簡單測試局域網中的電腦是否連通.這些電腦的ip範圍從192.168.0.101到192.168.0.200.
import subprocess

cmd="cmd.exe"
begin=101
end=200
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()

1、搭建開發環境

linux:    

1、安裝開發環境

sudoapt-getinstallopenjdk-6-jdk
sudoapt-getinstalleclipse
python一般Linux自帶

在eclipase中,InstallNewSoftware 
這是地址:Location:http://pydev.org/updates(PyDev的更新地址)

選擇PyDev下的PyDevforEclipse,其他的不選
安裝之後重啓eclipse

2、 配置PyDev插件
 
PyDev->Interpreter-Python,New一個Python解釋器,填上解釋器名字和路徑,路徑選相應的python.exe。
 File->New->Project,選PyDev下的PyDevProject,Grammer和Interpreter選相應的版本,Finish。
 
windows:

1、下載工具jthon(http://wiki.python.org/jython/DownloadInstructions),下載後雙擊執行該jar包.   第一步時選擇所有,包括所有源. 

2、在DOS命令窗口執行批處理。 
cmd進入命令行狀態。到安裝目錄c:/jthon2.5.5/執行jython.bat。 

3、在eclipse中安裝jthon插件 
在help->softupdate->add sites 輸入:windowhttp://pydev.sourceforge.net/updates/ 下載完後。選中這些下載選項。後點直接安裝

4、配置jython. 
在window-->屬性->pydev->interpreter-jython->new->瀏覽你安裝jthon的目錄(c://jython2.5.5.)指向jython.jar.點擊應用。然後點擊ok. 


2、Hello Python

print "Hello Python"
Python就是如此神奇

3、國際化的語言支持

# -*- coding: GBK -*- 
print "歡迎來的Python的世界!" # 使用中文
raw_input("Press enter key to close this window");
可以這樣設置語言的支持

4、方便易用的計算器

a=100.0
b=201.1
c=2343
print (a+b+c)/c
python就是計算器?

5 、字符串

打印出預定義輸出格式的字符串:
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
Python怎麼訪問字符串呢?
word="abcdefg"
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "+b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "+c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "+d # All elements of word.
e=word[:2]+word[2:]
print "e is: "+e # All elements of word.
f=word[-1]
print "f is: "+f # The last elements of word.
g=word[-4:-2]
print "g is: "+g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "+h # The last two elements.
i=word[:-2]
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);



6 、列表 

word=['a','b','c','d','e','f','g']
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "
print b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "
print c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "
print d # All elements of word.
e=word[:2]+word[2:]
print "e is: "
print e # All elements of word.
f=word[-1]
print "f is: "
print f # The last elements of word.
g=word[-4:-2]
print "g is: "
print g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "
print h # The last two elements.
i=word[:-2]
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

Python有着簡易方便的數據類型

7、條件和循環語句

# Multi-way decision
x=int(raw_input("Please enter an integer:"))
if x<0:
x=0
print "Negative changed to zero"

elif x==0:
print "Zero"

else:
print "More"


# Loops List
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)

Python是藝術家!

8、函數

# Define and invoke function.
def sum(a,b):
return a+b


func = sum
r = func(5,6)
print r

# Defines function with default argument
def add(a,b=2):
return a+b
r=add(1)
print r
r=add(1,5)
print r

並且,介紹一個方便好用的函數:
# The range() function
a =range(5,10)
print a
a = range(-2,-7)
print a
a = range(-7,-2)
print a
a = range(-2,-11,-3) # The 3rd parameter stands for step
print a

Python竟然擁有如此完美的身材

9、文件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()

處理文件是不是很簡單?

10、異常處理
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!"

Python這樣來解決異常

11、類和繼承
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(2,3)

Pyhon最可愛的面嚮對象語言

12、包機制

每一個.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(1,2) # If using "import a" , then here should be "a.add_func"

帶有文件層級結構的導包
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(1,2)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章