Python 奇技淫巧
本文用作記錄,在使用python過(guò)程中遇到的一些奇技淫巧,有些代碼是本人所寫(xiě),有些則是python內(nèi)置函數(shù),有些則取之互聯(lián)網(wǎng),在此記錄,只為備份以及遺忘時(shí)方便查找。
本文將會(huì)持續(xù)更新,內(nèi)容僅限記錄一些常用好用卻又永遠(yuǎn)記不住的代碼或者模塊。
控制臺(tái)操作
控制臺(tái)不閃退:
os.system('pause')獲取控制臺(tái)大小:
rows, columns = os.popen('stty size', 'r').read().split()輸入輸出控制
解決輸入提示中文亂碼問(wèn)題:
raw_input(unicode('請(qǐng)輸入文字','utf-8').encode('gbk'))格式化輸出:
print a.prettify()接受多行輸入:
text="" while 1:data=raw_input(">>")if data.strip()=="stop":breaktext+="%s\n" % data print text --------------------------- >>1 >>2 >>3 >>stop 1 2 3標(biāo)準(zhǔn)輸入輸出:
# 標(biāo)準(zhǔn)輸入 sys.stdout.write("input") # 刷新緩沖區(qū) sys.stdout.flush()print的功能與sys.stdout.write類(lèi)似,因?yàn)?.x中print默認(rèn)就是將輸出指定到標(biāo)準(zhǔn)輸出中(sys.stdout)。
顏色控制
控制臺(tái)顏色控制(適用于windows):
WConio.textcolor(WConio.YELLOW) print "yellow" WConio.textcolor(WConio.BLUE) print "blue"輸出顏色控制(全平臺(tái)):
red = '\033[1;31m' green = '\033[1;32m' yellow = '\033[1;33m' white = '\033[1;37m' reset = '\033[0m’ print red+"color is red"+reset print green+"color is green"+reset進(jìn)度條控制
方案一:
from __future__ import division import sys,time j = '#' for i in range(1,61):j += '#'sys.stdout.write(str(int((i/60)*100))+'% ||'+j+'->'+"\r")sys.stdout.flush()time.sleep(0.1)方案二:
import sys import time for i in range(1,61):sys.stdout.write('#'+'->'+"\b\b")sys.stdout.flush()time.sleep(0.5)方案三:
from progressbar import * import time import os rows, columns = os.popen('stty size', 'r').read().split() #獲取控制臺(tái)size console_width=int(columns) total = 10 progress = ProgressBar() def test():'''進(jìn)度條函數(shù),記錄進(jìn)度'''for i in progress(range(total)):test2() def test2():'''執(zhí)行函數(shù),輸出結(jié)果'''content="nMask'Blog is http://thief.one"sys.stdout.write("\r"+content+" "*(console_width-len(content)))time.sleep(1)sys.stdout.flush() test()更多高級(jí)用法可以使用progressbar模塊。
系統(tǒng)操作
系統(tǒng)信息
獲取python安裝路徑:
from distutils.sysconfig import get_python_lib print get_python_lib獲取當(dāng)前python版本:
sys.version_info sys.version獲取當(dāng)前時(shí)間:
c=time.ctime() #自定義格式輸出 ISOTIMEFORMAT=’%Y-%m-%d %X’ time.strftime( ISOTIMEFORMAT, time.localtime() )查看系統(tǒng)環(huán)境變量:
os.environ["PATH"]獲取系統(tǒng)磁盤(pán):
os.popen("wmic VOLUME GET Name")獲取當(dāng)前路徑(包括當(dāng)前py文件名):
os.path.realpath(__file__)當(dāng)前平臺(tái)使用的行終止符:
os.linesep獲取終端大小:
rows, columns = os.popen('stty size', 'r').read().split() #python3以后存在可以使用os os.get_termial_size()退出程序
return:返回函數(shù)的值,并退出函數(shù)。
exit():直接退出。
sys.exit(): 引發(fā)一個(gè)SystemExit異常,若沒(méi)有捕獲錯(cuò)誤,則python程序直接退出;捕獲異常后,可以做一些額外的清理工作。
sys.exit(0):為正常退出,其他(1-127)為不正常,可拋異常事情供捕獲。(一般用于主線程中退出程序)
os._exit(0): 直接退出python程序,其后的代碼也不會(huì)執(zhí)行。(一般用于線程中退出程序)
網(wǎng)絡(luò)操作
域名解析為IP:
ip= socket.getaddrinfo(domain,'http')[0][4][0]獲取服務(wù)器版本信息:
Url = 'http://www.163.com' sock = urllib2.urlopen(sUrl) sock.headers.values()文件操作
open函數(shù),使用wb、rb代替w、r:
with open("test.txt","wr") as w:w.write("test")這種寫(xiě)法可以兼容python2/3。
輸出一個(gè)目錄下所有文件名稱:
def search(paths):if os.path.isdir(paths): #如果是目錄files=os.listdir(paths) #列出目錄中所有的文件for i in files:i=os.path.join(paths,i) #構(gòu)造文件路徑search(i) #遞歸elif os.path.isfile(paths): #如果是文件print paths #輸出文件名文件查找:
import glob print glob.glob(r"E:/*.txt") #返回的是一個(gè)列表 # 查找文件只用到三個(gè)匹配符:”*”, “?”, “[]“ # ”*”匹配0個(gè)或多個(gè)字符; # ”?”匹配單個(gè)字符; # ”[]“匹配指定范圍內(nèi)的字符,如:[0-9]匹配數(shù)字。查找指定名稱的文件夾的路徑:
def search(paths,file_name,tag,lists):if os.path.isdir(paths): #如果是目錄if file_name==tag: #如果目錄名稱為taglists.append(paths) #將該路徑添加到列表中else: #如果目錄名稱不為tagtry:files_list=os.listdir(paths) #列出目錄中所有的文件for file_name in files_list:path_new=os.path.join(paths,file_name) #構(gòu)造文件路徑search(path_new,file_name,tag,lists) #遞歸except: #遇到特殊目錄名時(shí)會(huì)報(bào)錯(cuò)passelif os.path.isfile(paths): #如果是文件passreturn lists數(shù)據(jù)操作
字符串推導(dǎo):
a="True" b=a if a=="True" else "False" >>>print b Trueformat方法拼接字符串與變量:
a="{test} abc {test2}".format(test="123",test2="456") >>>>print a 123 abc 456 或者: a="{},{}".format(1,2) >>>>>print a 1,2去掉小數(shù)點(diǎn)后面的數(shù)字:
a=1.21311 b=Int(math.floor(a))字符串倒置:
>>> a = "codementor" >>> a[::-1]字符串首字母變大寫(xiě):
info = 'ssfef' print info.capitalize() print info.title()返回一個(gè)字符串居中,并使用空格填充至長(zhǎng)度width的新字符串:
"center string".center(width) #width設(shè)置為控制臺(tái)寬度,可控制輸出的字符串居中。列舉所有字母:
print string.ascii_uppercase 所有大寫(xiě)字母 print string. ascii_lowercase 所有小寫(xiě)字母 print string.ascii_letters 所有字母(包括大小寫(xiě))列表操作
列表去重:
ids = [1,4,3,3,4,2,3,4,5,6,1] ids = list(set(ids))判斷列表為空:
a=[] if not a:列表運(yùn)算:
a=[1,2,3] b=[3,4,5] set(a)&set(b) 與 set(a)|set(b) 或 set(a)-set(b) 非單列表元素相加:
a = ["Code", "mentor", "Python", "Developer"] >>> print " ".join(a) Code mentor Python Developer多列表元素分別相加:
list1 = ['a', 'b', 'c', 'd'] list2 = ['p', 'q', 'r', 's'] >>> for x, y in zip(list1,list2): print x, y ap bq cr ds將嵌套列表轉(zhuǎn)換成單一列表:
a = [[1, 2], [3, 4], [5, 6]] >>> import itertools >>> list(itertools.chain.from_iterable(a)) [1, 2, 3, 4, 5, 6]列表內(nèi)元素相加:
a=[1,2,3](數(shù)字) sum(a)產(chǎn)生a-z的字符串列表:
map(chr,range(97,123))列表復(fù)制:
a=[1,2,3] b=a 當(dāng)對(duì)b進(jìn)行操作時(shí),會(huì)影響a的內(nèi)容,因?yàn)楣灿靡粋€(gè)內(nèi)存指針,b=a[:] 這樣就是單獨(dú)復(fù)制一份了。列表推導(dǎo)
if+else配合列表解析:
[i if i >5 else -i for i in range(10)]多層嵌套列表:
a=[[1,2],[3,4]] b=[for j in i for i in a] print b [1,2,3,4]生成一個(gè)生成器,調(diào)用next方法,可以減少內(nèi)存開(kāi)支:
a=(i else i+1 for i in b if i==1)字典推導(dǎo)
更換key與value位置:
dict={"a":1,"b":2} b={value:key for key value in dict.items()}字典操作
篩選出值重復(fù)的key:
list1=self.dict_ip.items() ddict=defaultdict(list)for k,v in list1:ddict[v].append(k)list2=[(i,ddict[i]) for i in ddict if len(ddict[i])>1]dict_ns=dict(list2)字典排序(py2):
file_dict={"a":1,"b":2,"c":3} file_dict_new=sorted(file_dict.iteritems(), key=operator.itemgetter(1),reverse=True) ##字典排序,reverse=True由高到低,itemgetter(1)表示按值排序,為0表示按key排序。字典值判斷:
b={"a":1} a=b.get("a","") #如果不存在a,則返回”” c=a if a else 0 #如果存在a,則返回a,不然返回0模塊操作
導(dǎo)入模塊時(shí),設(shè)置只允許導(dǎo)入的屬性或者方法:
fb.py: ----------------------- __all__=["a","b"] a="123" c="2345" def b():print “123” ----------------------- from fb import * 可以導(dǎo)入__all__內(nèi)定義的變量,a跟b()可以導(dǎo)入,c不行。如果不定義__all__則所有的都可以導(dǎo)入。導(dǎo)入上級(jí)目錄下的包:
sys.path.append("..") from spider.spider_ import spider_導(dǎo)入外部目錄下的模塊:
需要在目標(biāo)目錄下創(chuàng)建__init__.py文件,內(nèi)容隨便。增加模塊屬性:
有時(shí)候源代碼中,我們需要寫(xiě)上自己的名字以及版本介紹信息,可以用__name__的方式定義。 a.py: #! -*- coding:utf-8 -*- __author__="nMask"然后當(dāng)我們導(dǎo)入a這個(gè)模塊的時(shí)候,可以輸出dir(a)看看:
>>> import p >>> print dir(p) ['__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__'] >>> print p.__author__ nmas動(dòng)態(tài)加載一個(gè)目錄下的所有模塊:
目錄: ---test----a.py----b.py ---c.py c.py導(dǎo)入test下面的所有模塊: for path in ["test"]:for i in list(set([os.path.splitext(i)[0] for i in os.listdir("./"+path)])):if i!="__init__" and i!=".DS_Store": ##排除不必要的文件import_string = "import path+"."+i+"exec import_string #執(zhí)行字符串中的內(nèi)容函數(shù)操作
eval/exec:
def test(content):print content exec(“test(‘a(chǎn)bc')”)輸出:abc
說(shuō)明:exec函數(shù)沒(méi)有返回值
輸出:abc
說(shuō)明:eval函數(shù)有返回值
裝飾器
輸出當(dāng)前時(shí)間裝飾器:
def current_time(aclass):def wrapper():print "[Info]NowTimeis:",time.ctime()return aclass()return wrapperitertools迭代器:
p=product(["a","b","c","d"],repeat=2) ---- [("a","a"),("b","b")......]reduce函數(shù):
函數(shù)本次執(zhí)行的結(jié)果傳遞給下一次。
enumerate函數(shù)
輸入列表元素以及序列號(hào)
函數(shù)超時(shí)時(shí)間設(shè)置
利用signal設(shè)置某個(gè)函數(shù)執(zhí)行的超時(shí)時(shí)間:
import time import signaldef test(i):time.sleep(0.999)#模擬超時(shí)的情況print "%d within time"%(i)return idef fuc_time(time_out):# 此為函數(shù)超時(shí)控制,替換下面的test函數(shù)為可能出現(xiàn)未知錯(cuò)誤死鎖的函數(shù)def handler(signum, frame):raise AssertionErrortry:signal.signal(signal.SIGALRM, handler)signal.alarm(time_out)#time_out為超時(shí)時(shí)間temp = test(1) #函數(shù)設(shè)置部分,如果未超時(shí)則正常返回?cái)?shù)據(jù),return tempexcept AssertionError:print "%d timeout"%(i)# 超時(shí)則報(bào)錯(cuò)if __name__ == '__main__':for i in range(1,10):fuc_time(1)函數(shù)出錯(cuò)重試:
利用retrying模塊實(shí)現(xiàn)函數(shù)報(bào)錯(cuò)重試功能
如果我們運(yùn)行have_a_try函數(shù),那么直到random.randint返回5,它才會(huì)執(zhí)行結(jié)束,否則會(huì)一直重新執(zhí)行,關(guān)于該模塊更多的用法請(qǐng)自行搜索。
程序操作
Ctrl+C退出程序
利用signal實(shí)現(xiàn)ctrl+c退出程序。
程序自重啟
利用os.execl方法實(shí)現(xiàn)程序自重啟
總結(jié)
以上是生活随笔為你收集整理的Python 奇技淫巧的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 手把手教你完成CSDN对接百度统计 看完
- 下一篇: range方法在Python2和Pyth