為什么使用Python,Python應(yīng)用場(chǎng)合有什么
Admin 2022-09-23 群英技術(shù)資訊 807 次瀏覽
很多朋友都對(duì)“為什么使用Python,Python應(yīng)用場(chǎng)合有什么”的內(nèi)容比較感興趣,對(duì)此小編整理了相關(guān)的知識(shí)分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲,那么感興趣的朋友就繼續(xù)往下看吧!假設(shè)我們有這么一項(xiàng)任務(wù):簡(jiǎn)單測(cè)試局域網(wǎng)中的電腦是否連通.這些電腦的ip范圍從192.168.0.101到192.168.0.200.
思路:用shell編程.(Linux通常是bash而Windows是批處理腳本).例如,在Windows上用ping ip 的命令依次測(cè)試各個(gè)機(jī)器并得到控制臺(tái)輸出.由于ping通的時(shí)候控制臺(tái)文本通常是"Reply from … " 而不通的時(shí)候文本是"time out … " ,所以,在結(jié)果中進(jìn)行字符串查找,即可知道該機(jī)器是否連通.
實(shí)現(xiàn):Java代碼如下:
String cmd="cmd.exe ping ";
String ipprefix="192.168.10."; int begin=101; int end=200;
Process p=null; for(int i=begin;i<end;i++){
p= Runtime.getRuntime().exec(cmd+i);
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = reader.readLine()) != null)
{
//Handling line , may logs it. }
reader.close();
p.destroy();
}
這段代碼運(yùn)行得很好,問題是為了運(yùn)行這段代碼,你還需要做一些額外的工作.這些額外的工作包括:
當(dāng)然,用C/C++同樣能完成這項(xiàng)工作.但C/C++不是跨平臺(tái)語言.在這個(gè)足夠簡(jiǎn)單的例子中也許看不出C/C++和Java實(shí)現(xiàn)的區(qū)別,但在一些更為復(fù)雜的場(chǎng)景,比如要將連通與否的信息記錄到網(wǎng)絡(luò)數(shù)據(jù)庫.由于Linux和Windows的網(wǎng)絡(luò)接口實(shí)現(xiàn)方式不同,你不得不寫兩個(gè)函數(shù)的版本.用Java就沒有這樣的顧慮.
同樣的工作用Python實(shí)現(xiàn)如下:
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()
對(duì)比Java,Python的實(shí)現(xiàn)更為簡(jiǎn)潔,你編寫的時(shí)間更快.你不需要寫main函數(shù),并且這個(gè)程序保存之后可以直接運(yùn)行.另外,和Java一樣,Python也是跨平臺(tái)的.
有經(jīng)驗(yàn)的C/Java程序員可能會(huì)爭(zhēng)論說用C/Java寫會(huì)比Python寫得快.這個(gè)觀點(diǎn)見仁見智.我的想法是當(dāng)你同時(shí)掌握J(rèn)ava和Python之后,你會(huì)發(fā)現(xiàn)用Python寫這類程序的速度會(huì)比Java快上許多.例如操作本地文件時(shí)你僅需要一行代碼而不需要Java的許多流包裝類.各種語言有其天然的適合的應(yīng)用范圍.用Python處理一些簡(jiǎn)短程序類似與操作系統(tǒng)的交互編程工作最省時(shí)省力.
足夠簡(jiǎn)單的任務(wù),例如一些shell編程.如果你喜歡用Python設(shè)計(jì)大型商業(yè)網(wǎng)站或者設(shè)計(jì)復(fù)雜的游戲,悉聽尊便.
安裝完P(guān)ython之后(我本機(jī)的版本是2.5.4),打開IDLE(Python GUI) , 該程序是Python語言解釋器,你寫的語句能夠立即運(yùn)行.我們寫下一句著名的程序語句:
print "Hello,world!"
并按回車.你就能看到這句被K&R引入到程序世界的名言.
在解釋器中選擇"File"–“New Window” 或快捷鍵 Ctrl+N , 打開一個(gè)新的編輯器.寫下如下語句:
print "Hello,world!"
raw_input("Press enter key to close this window! ");
保存為a.py文件.按F5,你就可以看到程序的運(yùn)行結(jié)果了.這是Python的第二種運(yùn)行方式.
找到你保存的a.py文件,雙擊.也可以看到程序結(jié)果.Python的程序能夠直接運(yùn)行,對(duì)比Java,這是一個(gè)優(yōu)勢(shì).
我們換一種方式來問候世界.新建一個(gè)編輯器并寫如下代碼:
print "歡迎來到奧運(yùn)中國(guó)!"
raw_input("Press enter key to close this window!");
在你保存代碼的時(shí)候,Python會(huì)提示你是否改變文件的字符集,結(jié)果如下:
# -*- coding: cp936 -*-
print "歡迎來到奧運(yùn)中國(guó)!"
raw_input("Press enter key to close this window! ");
將該字符集改為我們更熟悉的形式:
# -*- coding: GBK -*-
print "歡迎來到奧運(yùn)中國(guó)!" # 使用中文的例子
raw_input("Press enter key to close this window");
程序一樣運(yùn)行良好.
用微軟附帶的計(jì)算器來計(jì)數(shù)實(shí)在太麻煩了.打開Python解釋器,直接進(jìn)行計(jì)算:
a=100.0 b=201.1 c=2343 print (a+b+c)/c
可以如下打印出預(yù)定義輸出格式的字符串:
print """ Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to """
字符串是怎么訪問的?請(qǐng)看這個(gè)例子:
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)
請(qǐng)注意ASCII和UNICODE字符串的區(qū)別:
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);
類似Java里的List,這是一種方便易用的數(shù)據(jù)類型:
word=['a','b','c','d','e','f','g']
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: " print b # index1 and 2 elements of word.
c=word[:2]
print "c is: " print c # index0 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 # index3 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[圖片上傳中...(image-b4ced-1616074265420-0)] " word.append('h')
print word
# 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 ina:
print x, len(x)
# 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
并且,介紹一個(gè)方便好用的函數(shù):
# 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
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 forreading 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(2,3)
每一個(gè).py文件稱為一個(gè)module,module之間可以互相導(dǎo)入.請(qǐng)參看以下例子:
# 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"
module可以定義在包里面.Python定義包的方式稍微有點(diǎn)古怪,假設(shè)我們有一個(gè)parent文件夾,該文件夾有一個(gè)child子文件夾.child中有一個(gè)module a.py . 如何讓Python知道這個(gè)文件層次結(jié)構(gòu)?很簡(jiǎn)單,每個(gè)目錄都放一個(gè)名為_init_.py 的文件.該文件內(nèi)容可以為空.這個(gè)層次結(jié)構(gòu)如下所示:
parent
--__init_.py
--child
-- __init_.py
--a.py
b.py
那么Python如何找到我們定義的module?在標(biāo)準(zhǔn)包sys中,path屬性記錄了Python的包路徑.你可以將之打印出來:
import sys print sys.path
通常我們可以將module的包路徑放到環(huán)境變量PYTHONPATH中,該環(huán)境變量會(huì)自動(dòng)添加到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)
你會(huì)發(fā)現(xiàn)這個(gè)教程相當(dāng)?shù)暮?jiǎn)單.許多Python特性在代碼中以隱含方式提出,這些特性包括:Python不需要顯式聲明數(shù)據(jù)類型,關(guān)鍵字說明,字符串函數(shù)的解釋等等.我認(rèn)為一個(gè)熟練的程序員應(yīng)該對(duì)這些概念相當(dāng)了解,這樣在你擠出寶貴的一小時(shí)閱讀這篇短短的教程之后,你能夠通過已有知識(shí)的遷移類比盡快熟悉Python,然后盡快能用它開始編程.
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:[email protected]進(jìn)行舉報(bào),并提供相關(guān)證據(jù),查實(shí)之后,將立刻刪除涉嫌侵權(quán)內(nèi)容。
猜你喜歡
這篇文章主要介紹了Python解決爬蟲程序卡死問題,文章圍繞主題展開詳細(xì)內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
這篇文章主要介紹了Python中的內(nèi)存管理之python list內(nèi)存使用詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
這篇文章主要介紹了Python打印數(shù)據(jù)類型的全過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
Matlab 擅長(zhǎng)于操作矩陣,而圖像其實(shí)就是矩陣,這篇文章主要給大家介紹了關(guān)于matlab原始處理圖像幾何變換的相關(guān)資料,需要的朋友可以參考下
1.背景知識(shí) 階乘是基斯頓·卡曼(Christian Kramp,1760~1826)于 1808 年發(fā)明的運(yùn)算符號(hào)。一個(gè)正整數(shù)的階乘(factorial)是所有小于及等于該數(shù)的正整數(shù)的積,通俗的講也就是按順序從1乘到
推薦內(nèi)容
相關(guān)標(biāo)簽
成為群英會(huì)員,開啟智能安全云計(jì)算之旅
立即注冊(cè)關(guān)注或聯(lián)系群英網(wǎng)絡(luò)
7x24小時(shí)售前:400-678-4567
7x24小時(shí)售后:0668-2555666
24小時(shí)QQ客服
群英微信公眾號(hào)
CNNIC域名投訴舉報(bào)處理平臺(tái)
服務(wù)電話:010-58813000
服務(wù)郵箱:[email protected]
投訴與建議:0668-2555555
Copyright ? QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版權(quán)所有
增值電信經(jīng)營(yíng)許可證 : B1.B2-20140078 ICP核準(zhǔn)(ICP備案)粵ICP備09006778號(hào) 域名注冊(cè)商資質(zhì) 粵 D3.1-20240008