Python非阻塞读取文件

7
我想以非阻塞模式读取文件,所以我按照以下方式进行了操作。
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!!"

但是变量flag仍然代表着0。为什么呢?我认为它应该根据os.O_NONBLOCK进行更改。

当然,如果我调用fd.read(),那么它将在read()处被阻塞。

1个回答

10

O_NONBLOCK是一个状态标志,而不是描述符标志。因此,请使用F_SETFL设置文件状态标志,而不是F_SETFD,后者用于设置文件描述符标志

此外,请确保将整数文件描述符作为fcntl.fcntl的第一个参数传递,而不是 Python 文件对象。因此,请使用:

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

而不是

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

打印

O_NONBLOCK!!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接