gpt4 book ai didi

python非 block 读取文件

转载 作者:行者123 更新时间:2023-12-04 12:04:07 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于python非 block 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30172428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com