Python通過select實現非同步IO的方法

來源:互聯網
上載者:User

Python通過select實現非同步IO的方法

   本文執行個體講述了Python通過select實現非同步IO的方法。分享給大家供大家參考。具體如下:

  在Python中使用select與poll比起在C中使用簡單得多。select函數的參數是3個列表,包含整數檔案描述符,或者帶有可返迴文件描述符的fileno()方法對象。第一個參數是需要等待輸入的對象,第二個指定等待輸出的對象,第三個參數指定異常情況的對象。第四個參數則為設定逾時時間,是一個浮點數。指定以秒為單位的逾時值。select函數將會返回一組檔案描述符,包括輸入,輸出以及異常。

  在linux下利用select實現多路IO的檔案複製程式:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

#!/usr/bin/env python

import select

#匯入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對輸入所有輸入的檔案描述符進行監視

rs,ws,es = select.select([fromfd1,fromfd2],[],[])

for r in rs:

if r is fromfd1:

#當第一個檔案描述符可讀時,讀入資料

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()

  希望本文所述對大家的Python程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.