gpt4 book ai didi

python - 连续读取命名管道

转载 作者:行者123 更新时间:2023-11-28 16:33:17 25 4
gpt4 key购买 nike

在 Python 中连续读取命名管道的最佳方法是什么?

这是我当前的代码:

def read_commands():
try:
print "Creating read pipe..."
os.mkfifo(pipe_cmd) # Create pipe
print "Pipe created!"
except:
print "Pipe already exists"

with open(pipe_cmd, "r") as pipecmd:
while True:
try:
line = pipecmd.readline()
except:
print "Could not read cmd pipe"

if line != "":
print line

#time.sleep(1)

但是,当我运行这段代码时,它似乎从我的 CPU 中占用了大量资源(其中一个将达到 100%)。它在 1 秒的 sleep 中工作正常。但是,我需要连续读取管道以确保是否有新数据。有没有更好的方法来实现这一点?

这是我用 C++ 发送到管道的内容:

void write_pipe(){
ofstream pipe("/tmp/okccmd"); // Open the pipe
string data = "Hi";
pipe << data << endl;
pipe.flush();
}

谢谢!

最佳答案

select.poll 工作正常(至少对于 Linux,不确定 Windows 是否支持这个;但是 select.select ist afaik 可用)。只需查看文档,该模块在标准库中并有详细记录(无需了解操作系统 select() 函数的实际工作原理)。

文档: https://docs.python.org/3/library/select.html

注意:poll() 返回文件描述符列表,而不是文件对象。所以,你应该有一个将文件描述符映射到相应对象的字典(如果我只轮询一个文件,我也会有这个。

pollobj = select.poll()
polled_files = dict()

# the following two lines are reuired for every file
pollobj.register(my_file_obj, <EVENTMASK>)
polled_files[my_file_obj.fileno()] = my_file_obj

for fd, evt in pollobj.poll():
fileobj = polled_files[fd]
... process event for fileobj

关于python - 连续读取命名管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29688784/

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