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

來源:互聯網
上載者:User

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

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

  在使用poll()後返回輪詢對象,該對象支援以下方法:

  pollObj.register(fd,[,eventmask])第一個參數是註冊新的檔案描述符fd,fd要麼是一個整數檔案描述符,要麼可以帶有一個擷取檔案描述符的fileno()方法的對象。eventmask是一些按位或標記,這些標記指示要處理的事件。

  POLLIN: 用於讀取資料

  POLLPRI: 用於讀取緊急資料

  POLLOUT: 準備寫入

  POLLERR: 錯誤情況

  POLLHUP: 保持狀態

  POLLNVAL: 無效請求

  最後在迴圈中利用pollObj.poll()來進行對登入的檔案描述符進行輪詢。返回一元祖(fd,event)。其中fd是檔案描述符,event是指示時間的位元遮罩。至需要將event與對應的時間進行&測試即可。

  利用poll建立對一個多路檔案複製程式,代碼如下:

  ?

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

41

42

43

44

45

46

47

48

49

50

51

52

53

54

#!/usr/bin/env python

import select

BLKSIZE=8192

def readwrite(fromfd,tofd):

readbuf = fromfd.read(BLKSIZE)

if readbuf:

tofd.write(readbuf)

tofd.flush()

return len(readbuf)

def copyPoll(fromfd1,tofd1,fromfd2,tofd2):

#定義需要監聽的事件

READ_ONLY = (select.POLLIN |

select.POLLPRI |

select.POLLHUP |

select.POLLERR )

totalbytes=0

if not (fromfd1 or fromfd2 or tofd1 or tofd2) :

return 0

fd_dict = {fromfd1.fileno():fromfd1,fromfd2.fileno():fromfd2}

#建立poll對象p

p=select.poll()

#利用poll對象p對需要監視的檔案描述符進行註冊

p.register(fromfd1,READ_ONLY)

p.register(fromfd2,READ_ONLY)

while True:

#輪詢已經註冊的檔案描述符是否已經準備好

result = p.poll()

if len(result) != 0:

for fd,events in result:

if fd_dict[fd] is fromfd1:

if events & (select.POLLIN|select.POLLPRI):

bytesread = readwrite(fromfd1,tofd1)

totalbytes+=bytesread

elif events & (select.POLLERR):

p.unregister(fd_dict[fd])

if fd_dict[fd] is fromfd2:

if events & (select.POLLIN|select.POLLPRI):

bytesread = readwrite(fromfd2,tofd2)

totalbytes+=bytesread

elif events & (select.POLLERR):

p.unregister(fd_dict[fd])

if bytesread <= 0:

break

return totalbytes

def main():

fromfd1 = open("/etc/fstab","r")

fromfd2 = open("/root/VMwareTools-8.8.1-528969.tar.gz","r")

tofd1 = open("/root/fstab","w+")

tofd2 = open("/var/passwd","w+")

totalbytes = copyPoll(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.