Python通過select實(shí)現(xiàn)異步IO的方法
本文實(shí)例講述了Python通過select實(shí)現(xiàn)異步IO的方法。分享給大家供大家參考。具體如下:
在Python中使用select與poll比起在C中使用簡(jiǎn)單得多。select函數(shù)的參數(shù)是3個(gè)列表,包含整數(shù)文件描述符,或者帶有可返回文件描述符的fileno()方法對(duì)象。第一個(gè)參數(shù)是需要等待輸入的對(duì)象,第二個(gè)指定等待輸出的對(duì)象,第三個(gè)參數(shù)指定異常情況的對(duì)象。第四個(gè)參數(shù)則為設(shè)置超時(shí)時(shí)間,是一個(gè)浮點(diǎn)數(shù)。指定以秒為單位的超時(shí)值。select函數(shù)將會(huì)返回一組文件描述符,包括輸入,輸出以及異常。
在linux下利用select實(shí)現(xiàn)多路IO的文件復(fù)制程序:
#!/usr/bin/env python import select #導(dǎo)入select模塊 BLKSIZE=8192 def readwrite(fromfd,tofd): readbuf = fromfd.read(BLKSIZE) if readbuf: tofd.write(readbuf) tofd.flush() return len(readbuf) def copy2file(fromfd1,tofd1,fromfd2,tofd2): ''' using select to choice fds''' totalbytes=0 if not (fromfd1 or fromfd2 or tofd1 or tofd2) : #檢查所有文件描述符是否合法 return 0 while True: #開始利用select對(duì)輸入所有輸入的文件描述符進(jìn)行監(jiān)視 rs,ws,es = select.select([fromfd1,fromfd2],[],[]) for r in rs: if r is fromfd1: #當(dāng)?shù)谝粋€(gè)文件描述符可讀時(shí),讀入數(shù)據(jù) bytesread = readwrite(fromfd1,tofd1) totalbytes += bytesread if r is fromfd2: bytesread = readwrite(fromfd2,tofd2) totalbytes += bytesread if (bytesread <= 0): break return totalbytes def main(): fromfd1 = open("/etc/fstab","r") fromfd2 = open("/etc/passwd","r") tofd1 = open("/root/fstab","w+") tofd2 = open("/root/passwd","w+") totalbytes = copy2file(fromfd1,tofd1,fromfd2,tofd2) print "Number of bytes copied %d\n" % totalbytes return 0 if __name__=="__main__": main()
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
使用Python+OpenCV進(jìn)行卡類型及16位卡號(hào)數(shù)字的OCR功能
本文將使用Python+OpenCV實(shí)現(xiàn)模板匹配算法,以自動(dòng)識(shí)別卡的類型和以及16位卡號(hào)數(shù)字,通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-08-08jenkins+python自動(dòng)化測(cè)試持續(xù)集成教程
這篇文章主要介紹了jenkins+python自動(dòng)化測(cè)試持續(xù)集成教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python應(yīng)用開發(fā)之實(shí)現(xiàn)串口通信
在嵌入式開發(fā)中我們經(jīng)常會(huì)用到串口,串口通信簡(jiǎn)單,使用起來方便,且適用場(chǎng)景多。本文為大家準(zhǔn)備了Python實(shí)現(xiàn)串口通信的示例代碼,需要的可以參考一下2022-11-11