#!/usr/bin/env python #在環境變量env中找Python
#coding: utf8
1.自動補全
配置環境: 建立以下檔案
vim /usr/local/bin/tab.py
輸入:
import readline
import rlcompleter
readline.parse_and_bind('tab:complete')
存儲後設定 SPYTHONSTARTUP
vim ~/.bash_profile 增加以下内容
再最後的export PATH前加
PYTHONSTARTUP=/usr/local/bin/tab.py
export PATH PYTHONSTARTUP
儲存後修改可執行權限
chmod +x /usr/local/bin/tab.py
source ~/.bash_profile(馬上生效)
驗證
echo SPYTHONSTARTUP(有值即可)
補全
#source /python_note/tab.sh 即可
關鍵字查詢: improt keyword
keyword.kwlist
循環擷取 I %s %(ine for line in data)
思路: 根據功能分函數,函數先寫架構
cmp 比較大小
list('abcd') >>>['a','b','c','d']
int 可轉進制 int('10',base=2) base指定進制數
abs 傳回絕對值
divmod(10,3) >>>(3,1) 可得商和餘
pow 指數運算,即幾次方
round 四舍五入 round(5.0/3,2)
hex 16進制數
oct 8進制
bin 2進制
ord ACCII碼
chr 轉為ACCII編碼
range(5) 生成0~5的清單
from random improt randint
randint(1,100) 随機生成一個(1,100)内的數
enumerate 傳回元組(下标,元素) 用list(enumerate(1,2))
reversed (反轉序列) 也可 [::-1]
sorted 排序
string.letters (字母大小寫清單)
string.digits (數字清單)
%15s%5s%('name','ager') 格式對齊
%-15s%-5s%('name','ager')左對齊
%s%s%(-10,'name',-5,'ager') *占位 -10和-5
string.centen(48) 居中字元串
string.capitalize() 首字母大寫
string.ljust(40,#) 左對齊
string.rjust(40,#)右對齊
string.count('l') 統計l出現次數
string.endswith('o') 是否以O結尾
string.startswith('e') 是否e開頭
string.islower 是否小寫,有任一大寫則傳回flase
string.isupper 是否大寫,有任一小寫則傳回flase
string.isdigit 是否數字
string.isacpha 是否字母
string.isalnum 是否數字和字母
string.strip 去除字元串兩端的空白,可加參數去除指定
string.strip('!') 去除兩端!字元串,不去除中間
string.lstrip() 去除左端空白
string.rstrip() 去除右端空白,
** string.rstrip('\r\n') 去除右端\r,\n,\r\n
string.vpper 小寫轉大寫
string.sqlit('.') 以.切割字元串,傳回清單
string.replace('o','a') 把o替換為a
improt subprocess 執行系統指令子產品
subprocess.call('ls -l /home',shell=True)
string.Template() 字元串子產品
data=f.read().decode('gb1803')
f.write(date.encode('utf8'))
清單切片增加:
alist=[10,11,12,13,'zh','li',30]
alist[5:5]=['ww','zl'] (清單中間插入)
alist=[10,11,12,13,'zh','ww','zl','li',30]
清單删除
del alist[-1] 删除最後一項
alist.pop() 删除最後一項并傳回删除項
alist.pop(3) 删除下标3的項
alist.remove(12) 根據值删除,相同值時隻删第一個
alist.count(10) 統計10出現次數
alist.extend() 拆分元素增加
alist.index('new') 傳回元素的下标,多個時隻傳回第一個,無則報錯
alist.insert(0,200) 向下标0插入200
alist.reverse() 反轉清單
alist.sort() 排序,預設升序排列
random.shuffle(alist) 打亂排序
alist.sort(reversed=True) 排序時反轉
alist.len() 擷取長度
alist.max() 擷取最大值
alist.min() 最小值
字元串拼接
str_list=['h','e','o']
'.'.join(str_list) #以.号連接配接
輸出'h.e.o'
多用清單,效率高
字典
adict['name'] 字典通路
for key in adict:
print "%s:%s" %(key,adict[key]) 字典循環
"(name)s:%(age)s"% adict 擷取值
adict.pop(key) 彈出健
adict.popitem() 随機彈
adict.setdefault('mail','bobcatudo') 有則不變更
adict.keys() 傳回健
adict.values() 傳回值
adict.items() 傳回健和值
adict.update(bdict) 字典相加
多if 判斷多個條件時某些值時用字典
cmds = {'0':push_it,'1':pop_it,'2':view_it}
choice=raw_input(prompt).strip()[0] #去掉輸入的空格并擷取第一個值
cmds[choice]() #用字典比對擷取對應的值得調用函數
元組
tuple()
建立單元組時要在後面加,
a=('10',)
元組不可變,但元組中的清單可以變
atuple=(1,[],2)
atuple[1].append(10)
atuple[1].append(20)
結果是 atuple=(1,[10,20],2)
max() 傳回最大
mint() 傳回最小
alist=['hello','word']
enumerate(alist) 傳回函數對象
list(enumerate(alist))
集合: 集合可以去重 set(['1','2'])
判斷: big=x if x>y else y
生成器表達式:不真正建立列,傳回一個生成器,使用時才生成
(expr for iter_var in iterable if (ond_expr))
print "\r" # \r不換行,後面加,連接配接。
%c 數字轉化為ACCII
%s 先轉化為字元串後
%d 整數類型,隻留整數
% d 前面留白格相容負數
%05d 前面空格補0
%+5d 正數前面顯示+号
%f 浮點數
%5.3f 寬度為5,小數為3位
%i int
%e 科學計數法
%o 8進制數
%#o 顯示字首
花括号格式化
" {} is {} yesas old".format('bob','23')
推薦用花括号格式化
" {0[0]} is {0[1]} yesas old".format(alist)
第一列左對齊寬度為8,第二列為寬度5左對齊,<左對齊, >有對齊
" {0:8s} is {1:<5d} yesas old".format('bob','23')
字元串模版
ori_txt='HI ${name},I WILL SEE YOU ${day}'
t=string.Template(ori_txt)
t.substitute(name='bob',day='tomorrow')
調用系統指令建議使用 subprocess
subprocess.call('ls /home', shell=True)
字典:{} 花括号,無序。
<a href="mailto:br/"></a>
<a href="mailto:br/">{}.fromkeys(('tom','bob','alice'),7) #值固定為7時可以批量建立 輸出:{'bob':7,'alice':7,'tom':7} adict['key'] 通路字典 adict.pop['key'] 删除字典 del adict['key'] 删除字典 adict.popitem() 随機删除值并傳回删除的值 adict.clear 清除字典</a>
<a href="mailto:br/">adict ={'age':7,'name':'bob'} '%(name)s:%(age)s' % adict</a>
<a href="mailto:br/">a=adict.copy() 深複制,值互不影響 clist=alist[:] 清單複制,值互不影響 adict.get('key') 取出值,不存在傳回none adict.get('key',23) 取出值,不存在傳回23 adict.get('key','nout found') 取出值,不存在傳回not found adict.setdefault('age',20) 設定值,存在則不改變. adict.keys() 擷取key的清單 adict.items() 擷取值和key的清單 adict.values()擷取值的清單</a>
<a href="mailto:br/">bdict={'age':23,'name':'bob','emil':'[email protected]'} {value:key for key,value in bdict.items()} #key和value對換,注意value有相同值時會丢項目</a>
<a href="mailto:br/">adict.update(bdict) 更新字典,可以把bdict合并到adict裡</a>
<a href="mailto:br/">隐藏密碼輸入 import getpass getpass.getpass("password")</a>
<a href="mailto:br/">集合 aset= set ('abc') bset= set ('cde') aset & base 等于 set([c]) 交集 aset | base 等于 set([a b c d e]) 交集 aset - bset 等于 set ([a b]) 差補,即a裡有,b裡沒有,可以做2個檔案的比較差異。</a>
<a href="mailto:br/">set.add() 添加成員 set.remove() 移除成員 set.update() 批量添加成員</a>
<a href="mailto:br/">批量執行指令,判斷每一個語句結果 commands = [ 'mkdir /tmp/adb', 'echo hello > /tmp/abc/myfile.txt', 'cat /tmp/abc/myfile.txt' ]</a>
<a href="mailto:br/">def fun0():</a>
<a href="mailto:br/">def fun1():</a>
<a href="mailto:br/">def fun2():</a>
<a href="mailto:br/">func_dict = {0:func0,1:func1,2:func2}</a>
<a href="mailto:br/">for i in range(len(commands)): ret_val=subprocess.call(commands[i],shell=True) if ret_val !=0: fun_dict[i]() break</a>
<a href="mailto:br/">疊代器 myiter= iter('abc') myiter.next() 到最後會報錯</a>
<a href="mailto:br/">for 循環可以便利所有類型。 生成器表達式,使用時才生成,節省記憶體 ('172.168.1.%s' %s i for i in range(1,255))</a>
<a href="mailto:br/">檔案處理 .readline() #以/n 結束為一行</a>
<a href="mailto:br/">flush() 立即同步到檔案</a>
<a href="mailto:br/">\r #回車不換行,即在同一行中</a>
<a href="mailto:br/">os os.sep # / os.curdir #. os.pardir #.. os.linesep #\n os.mknod('test.txt') #建立空檔案 os.symlink('/etc/host','zhuji') #快捷方式 os.chmod('test.txt',0644) #0代表8進制,需寫。</a>
<a href="mailto:br/">cPickle(c語言寫的,數度快),Pickle子產品 存儲對象類型,友善取出。 adict={'name':'bob'} f=open('/tmp.tx','w') cPickle.dump(adict,f) #儲存字典到文本 cPickle.load(f) #讀取檔案中的資料</a>
<a href="mailto:br/">錯誤: keyboardinterrupt :使用者中斷執行 EOFError :沒有内健輸入,到達EOF标記 , IOError :輸入輸出操作失敗</a>
<a href="mailto:br/">分析可能産生異常的位置再加try 一個try 可以有多個 except 如: except (keyboardinterrupt,eoferror) #多個錯誤類型用()包含 except(valueError) except valueerror ,e : # e儲存錯誤資訊 BaseException 所有異常 keyboardinterrupt #使用者中斷 即ctrl+c 取消 eoferror 沒有内健輸入 即ctrl+d IOError 輸入/輸出操作失敗 ,打開不存在的檔案 try: except: else: #沒報錯才執行 finally: #都執行</a>
<a href="mailto:br/">with 可以簡化代碼 如: with open('/etc/fstab') as fs: print fs.readline() 不必用fs.clock 關閉郵件</a>
<a href="mailto:br/">定義異常 if not 0 <age<150: raise ValueError , "age out of rang" #必須為已知異常 斷言異常 assert 0<age<150 ,"age out of rang" #不在0和150之間,就彈異常</a>
<a href="mailto:br/">fun() b=fun #等于b引用fun的空間</a>
<a href="mailto:br/">def fun (age,name='bob') #預設參數=需放後面 print '%s:%s' (name,age)</a>
<a href="mailto:br/">函數參數組 def get_args(*arge) print args</a>
<a href="mailto:br/">get_args(10,20,30)</a>
<a href="mailto:br/">def get_kwargs(**kwargs): #字典接受資料 print jiejiw get_kwargs(name='jj',age=23)</a>
<a href="mailto:br/">info=['bob',23] get_info(*info) #代表傳入清單的2個參數</a>
<a href="mailto:br/">info_dict={'name':'bob','aee':34} get_info(**info_dict) #拆開字典,傳入值</a>
<a href="mailto:br/">choice('+-') 随機選擇一項</a>
<a href="mailto:br/">匿名函數 a= lambda x,y:x+y #定義匿名函數 a(20,30)</a>
<a href="mailto:br/">字典使用匿名函數 mcds={'+': lambda x,y:x+y,'-':lambda x,y:x-y}</a>
<a href="mailto:br/">num_list=[randint(1,100) for i in range(10)] filter(函數,序列) ,函數或許序列的作為參數,函數結果為真保留,為假過濾 print filter(lambda x:x%2,num_list)</a>
<a href="mailto:br/">map(lambda x:x*2,num_list) #擷取序列的值 reduce(lambda x,y:x+y,num_list) #統計序列中的和,将第一個序列和第二個相加,結果在和第三個相加</a>
<a href="mailto:br/">vim 自動縮進 set ai</a>
<a href="mailto:br/">時間 data=time.strftime("%Y-%m-%d")</a>
<a href="mailto:br/">檢查檔案 md5sum</a>
<a href="mailto:br/">global #定義全局變量</a>
<a href="mailto:br/">偏函數 def add(x,y): return x+y</a>
<a href="mailto:br/">import functools add10=functools.partial(add,10) #可以固定X值的模式,第一個參數時函數,第二個參數沒指定y=10時,按順序指派</a>
<a href="mailto:br/">add10(3) #等于13</a>
<a href="mailto:br/">遞歸</a>
<a href="mailto:br/">例子:排序 ,彈出清單最後一個值和清單每項比較,小的放小清單,大的放大清單,最後放回 小+彈出的值+大,如果清單為空或1時,傳回清單 def sou(alist): if len(alist) == 0 or len(alist) == 1: return alist num = alist.pop() l = [] m = []</a>
<a href="mailto:br/">if name == 'main': alist = [random.randint(1, 100) for i in range(10)] print alist print sou(alist)</a>
<a href="mailto:br/">閉包 若内部變量想在内部的内部可以使用,則需為可變對象</a>
<a href="mailto:br/">def count(start=0): count=[start] def incr(): counter[0]+=1 return counter[0] return incr #閉包傳回的是函數 if name=='main': a=count() b=count(10) print a() print a() print b()</a>
<a href="mailto:br/">裝飾器</a>
<a href="mailto:br/">mport time def deco(fun): def timeit(): start=time.time() ret_val=fun() end=time.time() return ret_val,end-start return timeit #放回函數 @deco #裝飾器,将loop當deco的參數運作 def loop(): result=[] for i in range(1,11): result.append(i) time.sleep(0.3) return result</a>
<a href="mailto:br/">if name == 'main': print loop()</a>
<a href="mailto:br/">hashlib 子產品,作檔案校驗。 m=hashlib.md5('hello world!') m.hexdigest()</a>
<a href="mailto:br/">tarfile 直接通路tar檔案</a>
<a href="mailto:br/">tar=tarfile.open('2.tar.gz','w:gz') #建立tar檔案 tar.add('day01') #壓縮檔案 tar.close()</a>
<a href="mailto:br/">tar=tarfile.open('day01.tar.gz','r:') #自動識别壓縮方式 tar.extractall('/tmp/') #指定解壓位置</a>
<a href="mailto:br/">os.walk 擷取檔案夾下檔案清單 for path,foler,files in os.walk('/etc/') for each_file in files: os.path.join(path,each_file)</a>
<a href="mailto:br/">testcase/增量備份.py</a>
<a href="mailto:br/">class ClassName(object): #object 是基類或父類 count=0</a>
<a href="mailto:br/">ClassName.count #引用類</a>
<a href="mailto:br/">mc=ClassName() mc.count</a>
<a href="mailto:br/">mc.name='tom'</a>
<a href="mailto:br/">mc.dist name:tom 隻顯示執行個體的屬性</a>
<a href="mailto:br/">構造器函數 init 調用類時,先執行</a>
<a href="mailto:br/">class MyClass(object): def init(self,name): #綁定方法,需先執行個體化才能調用,self是變量名,可自己設,如下a=.. self.name=name #執行個體的屬性,外部需調用此屬性時,要綁定此屬性 def display_name(self): print name #顯示bob if name=='main': a=MyClass('bob') #執行個體對象化對象時,會把執行個體對象傳給self, 即a給self,是以隻傳一個參數即可 print a.name # 顯示bob a.display_name() b=MyClass('alice') b.display_name()</a>
<a href="mailto:br/">綁定方法 class Hotel(object): def init(self,room,cf=1.0,bf=15): self.room=room self.cf=cf self.bf=bf def calc_all(self,days=1): return (self.roomself.cf+self.bf) days if name == 'main': stroom=Hotel(200) print stroom.calc_all() print stroom.calc_all(2)</a>
<a href="mailto:br/">繼承類: addbook.py</a>
<a href="mailto:br/">class AddrBook(object): def init(self,name,phone): self.name=name self.phone=phone def get_phone(self): return self.phone</a>
<a href="mailto:br/">if name == 'main': bob=AddrBook('bob','1333333') alis=AddrBook('alis','144444') print bob.get_phone() bob.updata_phone('155555') print bob.get_phone()</a>
<a href="mailto:br/">email.py</a>
<a href="mailto:br/">import addbook class EmplAddrBook(addbook.AddrBook): #繼承上一個類 def init(self,name,phone,email):</a>
<a href="mailto:br/">組合:</a>
<a href="mailto:br/">class UserInfo(object): def init(self,phone,email): self.phone=phone self.email=email</a>
<a href="mailto:br/">class AddrBook(object): def init(self,name,phone,email): self.name=name self.info=UserInfo(phone,email) #引用上一個類定義的屬性</a>
<a href="mailto:br/">多重繼承 class A(object): def get_name(self): print 'in a' def start(self): print '' 20</a>
<a href="mailto:br/">class B(object): def display_name(self): print 'in b' def start(self): print '#' * 20</a>
<a href="mailto:br/">class C(A,B): pass if name == 'main': c=C() c.display_name() #繼承所有父類的方法 c.get_name() c.start() #先在A中查找,有就列印了</a>
<a href="mailto:br/">issubclass(B,A) #判斷B是否A的子類 isinstance(b,B) #判斷b是否B的執行個體 hasattr() #判斷一個對象是否另一個特定的屬性 getattr() #獲得一個對象的屬性 setattr() #設定一個對象的屬性 delattr() #删除一個對象的屬性</a>
<a href="mailto:br/">私有化 class A(object): def init(self): self.name='bob' #開頭的是私有化 def get_name(self): return self.__name</a>
<a href="mailto:br/">a =A() a.get_name()</a>
<a href="mailto:br/">class Books(object): def init(self,title,author): self.title=title self.author=author def str(self): #字元串初始化,比下面更易讀 return self.title def repr(self): return self.title #字元串初始化, def call(self): #方法調用 print '%s is jiw %s'%(self.title,self.author)</a>
<a href="mailto:br/">if name == 'main': py_book=Books('sss','wew') print py_book py_book()</a>
<a href="mailto:br/">正則:</a>
<a href="mailto:br/">. 比對任意字元 [..x-y..] 比對字元組裡的任意字元 [^..x-y..] 比對不再字元組裡的任意字元 \d 比對任意數字【0-9】 \D 非數字字元 \w 比對任意數字字母下劃線 【0-9a-zA-Z】 \W 非數字字母下劃線 \s 比對空白字元【\r\v\f\t\n】 \S 非空白字元</a>
<a href="mailto:br/">literal 比對字元串的值 re1|rel2 比對re1或re2</a>
<a href="mailto:br/">^ 比對字元串的開始 $ 比對字元串的結尾 \b 比對字元串的邊界 #egrep '\btom\b' ,隻比對 tom () 對正規表達式分組 \nn 比對已儲存的子組</a>
<a href="mailto:br/">import re</a>
<a href="mailto:br/">a=re.match('查找内容','查找目标') #正則查找,但隻比對開始,隐含有^ re.search('查找内容','查找目标') #正則查找,僅比對一個 a.group() #擷取查找内容</a>
<a href="mailto:br/">c=re.findall('the','apple the,teh the 22') #查找所有,結果放入清單,可以直接輸出 print c</a>
<a href="mailto:br/">c=re.finditer('the','apple the ,teh the 22') #傳回一個疊代器對象 for i in c: print i.group() #列印疊代器内容</a>
<a href="mailto:br/">IP位址正規表達式 ([0-9]{1,3}.){3}[0-9]{1,3}</a>
<a href="mailto:br/">MAC位址比對加符号 %/(..)(..)(..)(..)$/\1:\2:\:3\/g</a>
<a href="mailto:br/">complie 大量比對時用,可以提高效率 patt=re.compile('foo') m=patt.match('food') print m.group()</a>
<a href="mailto:br/">split 分隔符切割 mylist=re.split('.|-','hello-world.data') print mylist</a>
<a href="mailto:br/">import re z='firefox' dica={} data=open('access_log') for i in data: m=re.search(z,i) if m: ip=m.group() dica[ip]=dica.get(ip,0)+1 print dica</a>
<a href="mailto:br/">sub re.sub() #替換某一個字元 re.sub('X','MR','Hi X ,nice to meet you')</a>
<a href="mailto:br/">data='my phone number is :1588888696' m= re.search('.+(\d+)',data) print m.groups() #擷取了()裡的值</a>
<a href="mailto:br/">貪婪比對 ,即最長比對,即可能多的比對 m=re.search('.+?(\d+)',data) #?阻止貪婪比對 m.groups() ('1588888696')</a>
<a href="mailto:br/">socket函數與方法: 建立TCP伺服器 建立TCP伺服器的主要步奏: 1.建立伺服器套接字:s=socket.socket() 2.綁定位址到套接字:s.bind() 3.啟動監聽:s.listen() 4.接受客戶連接配接:s.accept() 5.與用戶端通信:recv()/send() 6.關閉套接字:s.close()</a>
<a href="mailto:br/">import socket</a>
<a href="mailto:br/">host='' #空串表示所有位址 port=1234 addr=(host,port)</a>
<a href="mailto:br/">s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #網絡的tcp的套接字 s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #套接字選項,允許程式退出後立即可以執行,1是允許 s.bind(addr)</a>
<a href="mailto:br/">s.listen(1) #為一個程式提供服務 while True: #持續連結 cli_sock,cli_addr = s.accept() #傳回一個套接字元組和位址,yum -y install telnet print "Client connected from:",cli_addr #telnet 127.0.0.1 1234 while True: cli_sock.send(" i c u \r \n") data= cli_sock.recv(1024) #每次接受1024位元組資料 if data.strip() == '' : break print data</a>
<a href="mailto:br/">s.close()</a>
<a href="mailto:br/">================================== 爬取圖檔</a>
data=html.read()
html.close
with open('a.jpg','w') as fobj:
fobj.write(data)
分析apache通路日志
編寫一個apche日志分析腳本
1.統計每個用戶端的通路apache伺服器的次數
2.将統計資訊通過字典的方式顯示出來
3.分别統計用戶端時firefox和msie的通路次數
4.分别使用函數式程式設計和面向對象程式設計的方式實作
import re
def count_patt(fname,patt):
result={}
cpatt=re.compile(patt)
def quick_sort(str_list):
if len(str_list)==0 or len(str_list) ==1:
return str_list
middle=str_list.pop()
smaller=[]
large=[]
for item in str_list:
if item[-1] < middle[-1]:
smaller.append(item)
else:
large.append(item)
return quick_sort(large) +[middle]+quick_sort(smaller)
if name == 'main':
log_file='access_log-2016077'
ip='^(\d+.){3}\d+'
br='Firefox|MSIE'
print count_patt(log_file,ip)
print count_patt(log_file,br)
多線程:
import threading
import subprocess,threading
def myiping(ip):
a=subprocess.call('ping -c2 -i0.1 %s &>/dev/null' % ip,shell=True)
if a:
print '%s is down'%ip
print '%s is up'%ip
net=['172.40.55.%s' %i for i in range(1,255)]
for i in net:
t=threading.Thread(target=myiping,args=[i]) #target是函數名,args是參數
t.start()
利用多線程實作ssh并發通路
import paramiko
host = '192.168.4.100'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username='root', password='123456')
ssh.exec_command('touch /hh22.txt')
stdin,stdout,stderr=ssh.exec_command('ls /') #将結果指派給3個變量
print stdout.read() #擷取輸出結果
4 案例4:利用多線程實作ssh并發通路
4.1 問題
編寫ssh用戶端腳本,主要要求如下:
python的paramiko子產品可以實作ssh用戶端的功能,使用起來也比較簡單。但是當伺服器非常多的時候,每台伺服器上執行完全相同的簡單操作,也會花費大量的時間。
通過ssh加上多線程,可以實作并發通路。為了将程式寫的靈活性更強,把要執行的指令以位置參數的方式來提供。
4.2 步驟
實作此案例需要按照如下步驟進行。
步驟一:編寫腳本
xinetd:
yum -y install xinetd
vim /etc/xinetd.d/pyserver
service pyserver
{
flags = NAMEINARGS
type = UNLISTED
socket_type = stream
port = 21345
protocol = tcp
wait = no
user = root
server = /root/lgh/ex1.py
server_args = /root/lgh/ex1.py
}
vim /root/lgh/ex1.py
#!/usr/bin/env python
import sys
sys.stdout.write('sdfe')
sys.stdout.flush() #重新整理緩存
父程序
os.fork()
celery 架構
import os
import time
pid=os.fork()
print pid
if pid:
print "in par"
time.sleep(15)
print "par ext"
print "in chi"
for i in range(5):
print time.ctime()
time.sleep(1)
print "ch exit"
父進通過os.wait()來得到子程序是否終止資訊
python3.0
依賴
yum -y install gcc gcc-c++ opensll-devel libffi-devel readline-devel
<a href="https://www.python.org/ftp/python/3.6.1/">https://www.python.org/ftp/python/3.6.1/</a>
字元串直接是UNICOOK
去除回車
print(line,end='')
input
5/3 直接傳回浮點
5//3 傳回整數
異常
except IndexError as e #2用逗号,3用as
raise valueerror,'valll.' #2用逗号
raise valueerror('xxxxx') #3用括号
range() 和2版本的xrange()一樣。
adict.keys 傳回對象,不是清單。
整數統一了,沒長整數
8進制數改成0o11
3也有可變集和和不可變集和
{} 是可變集和
frozenset([])是不可變集和。
資料庫
子產品 MySQL-python 1.2.5 py2.7
mysqlpy 2.1.7 py3.0
pip3 install PyMySQL 安裝組建
插入資料
import pymysql
conn=pymysql.connect(
host='127.0.0.1',
user='root',
port=3306,
passwd='123456',
db='test'
charset='utf8'
)
cursor=conn.cursor() #遊标,擷取SQL結果
sql1="insert into depar(dep_name) values(%s)"
result=cur.execute(sql1,('deve',)) #後面是元組,單元組要加逗号
print(result)
conn.commit()
cur.close() #關閉遊标
conn.close() #關閉資料庫
執行後放回1 是影響1行。
data=[('hr',),('op',),('财務',)]
result=cur.executemany(sql1,data) #多個資料
sql1="insert into depar(dep_name) values(%s,%s)"
data=[('hr','aa'),('op','bb'),('财務','cc')]
sql1="insert into salary(date,emp_id,basic,extra) values(%s,%s,%s,%s)"
data=(time.strftime('%Y-%m-%d'),1,10000,5000)
result=cur.execute(sql1,data) #多個資料
查詢
sql1="select * from departments"
result=cur.fetchone() #擷取一條資料
result2=cur.fetchmany(2) #擷取2條資料
cur.scroll(1,mode="ralative") #相對目前位置移動
result3=cur.fetchmany(2) #擷取2條資料
result3=cur.fetchall() #擷取全部資料
移動遊标擷取資料
cur.scroll(2,mode="absolute") #相對查詢結果位置移動
更新
sql1="updata salary set dep=%s where dep=%s"
result=cur.execute(sql1,('oppp','op')) #多個資料
删除
sql1="delete from salary where dep=%s"
result=cur.execute(sql1,('oppp',)) #多個資料
SQLalchemy
連接配接資料庫
安裝
pip3 install SQLalchemy
連接配接
資料庫類型+驅動://user:password@host/dbname[?key=value...] #[?連接配接參數]
from sqlalchemy import create_engine
engine=create_engine('mysql+pymysql://root:123456@localhost/dbtest',encoding='utf8',echo=True)
聲明映射
當使用ORM的時候,配置過程從描述資料庫表開始
通過自定義類映射相應的表
通過聲明系統實作類映射
首先通過聲明系統,定義基類
from sqlalchemy.ext.declarative import declarative_base
Base=declarative_base() #聲明基類
建立映射類
一旦建立了基類,就可以建立自定義映射類了
from sqlalchemy import Column,Integer,String
class Departments(Base):
tablename='departments'
dep_id=Column(Integer,primary_key=True)
dep_name=Column(String(20))
def repr(self):
return "<Department(dep_name='%s')>"% self.dep_name
#repr是可選項 輸出類的資訊,可print(Base)檢視
建立架構
類建構完成後,表的資訊将被寫入到表的中繼資料(metadata)
print(Departments.tablename) #檢視
建立表
Base.metadata.create_all(engine)
建立映射類的執行個體
建立執行個體時,并不會真正在表中添加記錄
dep_dev=Departments(dep_name='developments') #建立會話後才插入資料
print(dep_dev.dep_name)
print(dep_dev.dep_id)
建立會話類
ORM通路資料庫的句柄被稱做Session
from sqlalchemy.orm import sessionmaker
Session=sessionmaker(bind=engine)
如果在建立session前還未建立engine,操作如下
Session=sessionmaker()
Session.configure(bind=engine) #建立engine後執行
添加新對象
會話類的執行個體對象用于綁定到資料庫
執行個體化類的對象,并不打開任何連接配接
當執行個體初次使用,它将從Engine維護的連接配接池中獲得一個連接配接
當所有的事務均被commit或會話對象被關閉時,連接配接結束
session=Session()
session.add(dep_dev)
session.commit()
print(str(dep_dev.dep_id))
session.close()
。可以建立多個執行個體,批量添加記錄
。如果有中文,注意engine的參數
engine=create_engine('mysql+pymysql://root:123456@localhost/dbtest?charset=utf8',encoding='utf8',echo=True)
ORM映射關系也可用于表間建立外鍵限制
from sqlalchemy import Column,Integer,String,ForeignKey
class Employees(Base):
tablename='employees'
日期
from sqlalchemy import Column,Integer,String,ForeignKey,Date
class salary(Base):
tablename='salary'
日期插資料
from datetime import date
date1=date(2017,1,1)
bob1=Salary(date=date1,emp_id=4,basic=1000,extra=3000)
基本查詢
通過作用于session的query()函數建立查詢對象
query()函數可以接收多種參數
for instance in session.query(Departments).order_by(Departments.dep_id):
print(instance.dep_id,instance.dep_name)
使用ORM描述符進行查詢
傳回值是元組
for name,phone in session.query(Employees.name,Employees.phone ): #多字段
print(name,phone)
使用命名元組(即為元組下标命名,友善引用)
查詢對象傳回的是一個命名元組
名稱是類的名字,或是類中屬性的名字
for row in session.query(Departments,Departments.dep_name)
print(row.Departments,row.dep_name)
本文轉自sweak_h 51CTO部落格,原文連結:http://blog.51cto.com/13478354/2060017,如需轉載請自行聯系原作者