python Non-block read file

前端 未结 1 1943
名媛妹妹
名媛妹妹 2020-12-10 17:09

I want to read a file with non-block mode. So i did like below

import fcntl
import os

fd = open(\"./filename\", \"r\")
flag = fcntl.fcntl(fd.fileno(), fcntl         


        
相关标签:
1条回答
  • 2020-12-10 17:36

    O_NONBLOCK is a status flag, not a descriptor flag. Therefore use F_SETFL to set File status flags, not F_SETFD, which is for setting File descriptor flags.

    Also, be sure to pass an integer file descriptor as the first argument to fcntl.fcntl, not the Python file object. Thus use

    f = open("/tmp/out", "r")
    fd = f.fileno()
    fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
    

    rather than

    fd = open("/tmp/out", "r")
    ...
    fcntl.fcntl(fd, fcntl.F_SETFD, flag | os.O_NONBLOCK)
    flag = fcntl.fcntl(fd, fcntl.F_GETFD)
    

    import fcntl
    import os
    
    with open("/tmp/out", "r") as f:
        fd = f.fileno()
        flag = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
        flag = fcntl.fcntl(fd, fcntl.F_GETFL)
        if flag & os.O_NONBLOCK:
            print "O_NONBLOCK!!"
    

    prints

    O_NONBLOCK!!
    
    0 讨论(0)
提交回复
热议问题