python - 如何对文件使用 select() 函数

标签 python linux unix select

我试图理解 select() 在 Unix 中如何作为一个函数工作。 我有一个带套接字的工作示例,但在使用文件时遇到问题。在文件对象上使用 select() 时,它不会等待 - 而是直接继续执行后面的代码。

这个示例运行良好:

import socket
from select import select

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("127.0.0.1", 1111))
server_socket.listen(5)

# this function wait when server_socket descriptor will change
read, write, error = select([server_socket], [], [])

# this part print when I use "nc 127.0.0.1 1111"
print(server_socket)

但是当我尝试对文件使用相同的代码时,我得到了意想不到的结果。

import os
import fcntl
from select import select

file_descriptor = os.open('/tmp/test_file', os.O_CREAT)

# lock file? I try to use lockf, other options
fcntl.flock(file_descriptor, os.F_LOCK | os.O_SHLOCK)

# I think that select must wait when the file will be unlocked
read, write, error = select([], [file_descriptor], [])

# prints immediately
print(file_descriptor)

最佳答案

在 Unix 或像 osx 这样基于它的操作系统上,你应该使用管道。

来自 python 文档

Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.

关于python - 如何对文件使用 select() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734152/

相关文章:

python - 当需要多个groupby()和shift()时,如何在pandas数据框中逐行重新计算值?

php - 在 x86_64 GNU/Linux 上升级 PEAR

bash - 将两个文件粘贴到第一个文件

c - fork() 和 wait() 有两个子进程

c - 编写一个程序来像 C 中的命令行一样工作

python - 如果 <td> 标签具有属性,则抓取 <tr> 标签

python - 有没有更Pythonic的方法来进行这个字典迭代?

python - 迭代时修改list和dictionary,为什么在dict上会失败?

c - 使用 Bazel 构建内核模块

python - 如何以编程方式检查远程 Linux 机器上是否安装了 python 包?