python Non-block read file

爷,独闯天下 提交于 2019-11-28 04:04:45

问题


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.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, flag | os.O_NONBLOCK)
flag = fcntl.fcntl(fd, fcntl.F_GETFD)
if flag & os.O_NONBLOCK:
    print "O_NONBLOCK!!"

But the value flag still represents 0. Why..? i think i should be changed according to os.O_NONBLOCK

And of course, if i call fd.read(), it is blocked at read().


回答1:


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!!


来源:https://stackoverflow.com/questions/30172428/python-non-block-read-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!