python非块读fi

2024-04-25 23:02:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想读取一个非块模式的文件。 所以我喜欢下面

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()被阻塞。


Tags: 文件importreadifos模式openfilename
1条回答
网友
1楼 · 发布于 2024-04-25 23:02:26

O_NONBLOCK是状态标志,而不是描述符标志。因此,使用F_SETFLset File status flags,而不是F_SETFD,这是用于setting File descriptor flags

另外,请确保将整数文件描述符作为第一个参数传递给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!!

相关问题 更多 >