python非块读取文件 [英] python Non-block read file
问题描述
我想以非块模式读取文件.所以我喜欢下面
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!!"
但是值 flag
仍然代表 0.为什么..?我认为我应该根据 os.O_NONBLOCK
But the value flag
still represents 0.
Why..? i think i should be changed according to os.O_NONBLOCK
当然,如果我调用 fd.read(),它会在 read() 处被阻塞.
And of course, if i call fd.read(), it is blocked at read().
推荐答案
O_NONBLOCK
是状态标志,而不是描述符标志.因此使用 F_SETFL
来设置文件状态标志,不是 F_SETFD
,用于 设置文件描述符标志.
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.
另外,确保将整数文件描述符作为第一个参数传递给 fcntl.fcntl
,而不是 Python 文件对象.因此使用
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)
而不是
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!!
这篇关于python非块读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!