python: ASCII,unicode,utf-8 : pythoncoding:utf8: \033[;;m*******\033[0m : ‘‘‘ ‘‘‘ : if elif else for i in range(n,m,k)[n,m-1,k] break continue pass chr()[ASCII] ord()[ASCII] while else : a,b = 1,2 max = (a if a>b else b) python -: : : s[0] ::0;:-1: s[n:m:k]:cong : type() #: %d%i %f %s %% % : int():float():str():: s.find(t):t,,-1. s.index(t):t,. s.join(ls):sls. s.replace(old,new):. s.split(sep):sep,s.strip(t):t s.startswith(t):t:true :false s.endswith():zit:true :false s.isalnum():s.isalpha() :s.isdigit() :s.isupper():s.islower():s.upper():s.lower():s.swapcase():s.count(t):t: : :::,,: :[] :list():list(string):: append(string):extend(s):() insert(n,string):,pop():,.. remove():count():index():reverse():sort():len():max():min()::,,‘+‘‘*‘: pythonlist. [ x*x for x in range(1,11)] :X*X :for:,,. : :() :tuple() : ; ; :,,: a = (1,2,3) for i,j in enumerate(a): print i,j : index():count():. python: :,. :::: :{key1:value1,key2:value2,...} :dict():":"; ","; ,/ : :dict1[key] = value items()::,. keys():values():has_key():. del :len():update():,get():pop():popitem():clear():: for key in data: print key,data[key] : 1.,2.3.4.5.,6.set :{} :set() : len():add():remove():update(): pop():s|t: st s&t: st s-t: ,sts^t: pythonopen(‘file_name‘,‘r|w|a‘),file(‘file_name‘,‘r|w|a‘):,with :with open(‘file_name‘,‘r|w|a‘) as fileName: :open(,) r:,,. w:(),,a:(),,+:aa a+:,w+:,a+r+:,a+: readline():readlines():read():,tell():() seek():seek(,) write():writelines():flush():,close():mode:name:closed:: function def def () python. ,. pythondef,. ,,,python. pythonreturn,,. return,NONE,return,return ,NONE. : () python,,(),def,(),. : : :() python,,,. ,. :() ,global. : ,"name=value". python. ,,. :,‘name=value‘.(,.) . ,,,. : *args,,,*args. **kwargs,,**,"name=value",. : :,.,; lambda: ,,def. lambda,,,,. lambda. map() ,. lambdamapmap(lambda x:x**5,range(10)) enumerate: yield: generator() yield,Pythongenerator : . @:run = login(run) : ,..py ,,. if __name__ == ‘__main__‘: print __name__ : import module import module as module_alias from modules import names . : import sys print sys.path os() : os.name windows:nt,linux|unix:posix os.system():os.popen():,: os.getcwd():. os.chdir():os.walk():os.listdir():. os.mkdir():os.makedirs():; os.rmdir():; os.removedirs():.ops os.path.split():os.path.abspath(name):os.path.splitext():os.path.join(path,name):os.path.basename(path):os.path.dirname(path):: os.remove():os.rename():; os.path.exists():os.path.isfile():os.path.isdir():. os.path.islink():: os.stat():. os.getatime():os.getctime():os.getmtime():os.path.getsize(name):,nameOL random() random.randint(n,m):. ramdom.randrange([start],stop[,step]):,md5,hashlib import hashlib string = ‘abc‘ hash = hashlib.md5() hash.update(string) print hash.hexdiget() time197011:,,,time.struct_time 2016-6-29 11:07 Time: import time as t t.time(): UTCt.asctime():t.localtime():,t.sleep(secs):t.mktime(tuple):t.strptime(srring[.format]):. : dt = datetime.datetime.now() # print ‘(%Y-%m-%d %H:%M:%S %f): ‘, dt.strftime(‘%Y-%m-%d %H:%M:%S %f‘) # print ‘(%Y-%m-%d %H:%M:%S %p): ‘, dt.strftime(‘%y-%m-%d %I:%M:%S %p‘) # print ‘%%a: %s ‘ % dt.strftime(‘%a‘) # print ‘%%A: %s ‘ % dt.strftime(‘%A‘) # print ‘%%b: %s ‘ % dt.strftime(‘%b‘) # print ‘%%B: %s ‘ % dt.strftime(‘%B‘) # print ‘%%c: %s ‘ % dt.strftime(‘%c‘) # print ‘%%x%s ‘ % dt.strftime(‘%x‘) # print ‘%%X%s ‘ % dt.strftime(‘%X‘) # print ‘%s‘ % dt.strftime(‘%w‘) # print ‘%s‘ % dt.strftime(‘%j‘) # print ‘%s‘ % dt.strftime(‘%U‘) # %aWeb # %AWednesday # %b4Apr # %B4April # %c: 04/07/10 10:43:39# %d: # %f: [0,999999]# %H: 24[0, 23]# %I: 12[0, 11]# %j: [001,366]# %m: [01,12]# %M: [00,59]# %p: AMPM # %S: [00,61][00, 59]python~_~# %U: # %w: [0, 6]6# %W: # %x: 04/07/10# %X: 10:43:39# %y: 2# %Y: 4# %z: utc# %Z: # %%: %% => % def getTime(second=None): if second: ftime = t.strftime(‘%Y-%m-%d %H:%M:%S‘,t.gmtime(second)) else: ftime = t.strftime(‘%Y-%m-%d %H:%M:%S‘) #return ftime # # def getSecond(ftime=None): if ftime: if ftime.count(‘ ‘) != 0: second = t.mktime(t.strptime(ftime,‘%Y-%m-%d %H:%M:%S‘)) else: second = t.mktime(t.strptime(ftime,‘%Y-%m-%d‘)) else: second = t.time() return int(second) sys: sys.argv:List,sys.exit(n):,exit(0) sys.version:pythonsys.maxint:Intsys.maxunicode:Unicodesys.path:,PYTHONPATHsys.platform:: :: python(),.. : ,,. : NameError:: print a SyntaxError:i = 100 print i.1 IOError:/,f =file(‘1.txt‘) r.read() ImportError:,IndentationError:,IndexError:TypeError:AttributeError:,. : python: try: pass except ,e: pass Exception :try: -->except Exception1[,reason]: -->-->except Exception2[,reason]: -->-->except: -->exceptelse: -->finally: -->: assert expression[,reason] assert.,expression,,.. : (RE),,. re: pythonre. \d \D \w ,,\W ,,\s \S recompole()::compile(pattern,flags=0) findall():()(()),:findall(pattern,string[,flags]) match():,,None. :match(pattern,string) search():. ,,None. :search(pattern,string) split():,,max() :solit(pattern,string,max=0) sub()subn() :. subn()sub(),,:sub(pattern,repl,string,max=0) group():. group(i):i‘()‘groups():(). start():end():span():: conn=MySQLdb.connect(host="localhost",user="root",passwd="123",db="zj",charset="utf8") : host:,user:,passwd:,db:,port:MySQLTCP,3306 charset:: commit():rollback():cursor():,: cursor: execute(self,query,args):sql,executemany(self,query,args):sqlcursor: fetchall(self):. fetchmany(self,size=Nome):sizesize,cursor.arraysizeferchone(self):: : sql = ‘‘‘create table employee(name char(20)) ‘‘‘ cursor.execute(sql) : sql = ‘‘‘ insert into employee(name) values(‘zj‘) ‘‘‘ cursor.execute(sql) : sql = ‘‘‘select * from employee ‘‘‘ cursor.execute(sql) results = cursor.fetchall() for row in results: name = row[0] : sql = ‘‘‘ update employee set name = zz where id = %d ‘‘‘ %id cursor.execute(sql) : sql = "DELETE FROM EMPLOYEE WHERE AGE > ‘%d‘" cursor.execute(sql) psutil,cpu,,ps toplsofpmapwho iotop1.: disk = psutil.disk_partitions() for i in disk: print ":%s :%s" %(i.device,i.fstype) disk_use = psutil.disk_usage(i.device) print ":%fM,:%fM,%fM,%f%%,"%(disk_use.used/1024/1024,disk_use.free/1024/1024,disk_use.percent) 2cpudef cpu(): while True: time.sleep(1) cpu_liyonglv = psutil.cpu_percent() print "cpu%s%%"%cpu_liyonglv if cpu_liyonglv >15.0: baojing() def baojing(): i = 0 while i < 10 : i += 1 time.sleep(0.5) winsound.PlaySound("ALARM8",winsound.SND_ALIAS) cpu() 3memory = psutil.virtual_memory() print memory.used print memory.total ab = float(memory.used)/float(memory.total)*100 print "%.2f%%"%ab print psutil.swap_memory() 4#count = psutil.net_io_counters() print "\033[1;31;42m%s\033[0mbytes,\033[1;31;42m%s\033[0mbytes,%s,%s"%(count.bytes_sent,count.bytes_recv,count.packets_sent,count.packets_recv) users = psutil.users() print "",users[0].name #curent_time = psutil.boot_time() curent_time_1 = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(curent_time)) print curent_time_1 5#pidpid = psutil.pids() for k,i in enumerate(pid): try: proc = psutil.Process(i) print k,i,"%.2f%%"%(proc.memory_percent()),"%",proc.name(),proc.exe() except psutil.AccessDenied : print "psutil.AccessDenied" socket: .,socket. BSD UNIX,"",IP,. . 1.socketpython socet. socket,BSD Sockets API socketServer,,. : socket(family,type[,protocal]) ,,. socket.AF_UNIX:unixsocket.AF_INET:socket.AF_INET6:ipv6 socket.SOCK_STREAM:socket,for TCP socket.SOCK_DGRAM:socket,for UDP socket.SOCK_RAW:,ICMP,IGMPsocket.SOCK_SEQPACKET:TCP socket: s=socket.socket(socket.AF_INET,socket.SOCKE_STREAM) UDP socket: s=socket.socket(socket.AF_INET,socket.SOCKE_DGRAM) sockettcp,TCP,.UDP,. ,,.repr(data). socket s.bind(address): ,AF_INET,(host,port). s.listten(backlog):TCP.backlog,s.accept():TCP(conn,address),conn,.address. socket: s.connect(address):address.address(hostname,port),,socket.error. s.connect_ex(address):connect(address),0,errnosocket: s.rcv(bufize[,flag]):TCP.,bufsize.flag,s.send(string[,flag]):TCP.string.,string. s.sendall(string[,flag]):TCP.string,.None,. s.recvfrom(bufsize[,flag]):UDP.recv(),(data,address).data,address. s.sendto(string[,flag],address):UDP.,address(ipaddr,port),.s.close():s.getpeername():.. s.getsockname():.(ipaddr,port) s.setsockopt(level,optname,value):s.getsockopt(level,optname[,buflen]):s.settimeout(timeout):,timeout,.Noneconnect()s.getimeout():,.,None s.setblocking(flag):flag0recv()send()socket.error. s.makefile():tcp: : socket.socket(socket.AF_INET,socket.SOCKE_STREAM) s.bind() : s.listten() s.accept() ,s.recv(),s.sendall() ,s.close() tcp: socket.socket(socket.AF_INET,socket.SOCKE_STREAM) s.connect s.sendall() s.recv() ,s.close smtplibparamiko : 1.pyCrypto 2.ecdsa 3.paramiko SSHclient sftpclient threadthreading
原文地址:http://5180043.blog.51cto.com/5170043/1795996