[英]Reading a named pipe continuosly
What is the best way to read a named pipe continuously in Python? 在Python中连续读取命名管道的最佳方法是什么?
This is my current code: 这是我目前的代码:
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)
However, when I run this code it seems to be taking a lot of resources from my CPU (One of them will go to 100%). 但是,当我运行此代码时,它似乎从我的CPU中获取了大量资源(其中一个将达到100%)。 It works fine with the sleep of 1 second. 它可以在1秒的睡眠中正常工作。 However, I need to read the pipe continuously to make sure if there is new data . 但是,我需要连续读取管道以确保是否有新数据 。 Is there a better way to accomplish this? 有没有更好的方法来实现这一目标?
This is what I am sending to the pipe in C++: 这是我在C ++中发送到管道的内容:
void write_pipe(){
ofstream pipe("/tmp/okccmd"); // Open the pipe
string data = "Hi";
pipe << data << endl;
pipe.flush();
}
Thanks! 谢谢!
select.poll works fine (at least for Linux, not sure if Windows supports this; select.select ist afaik available, however). select.poll工作正常(至少对于Linux,不确定Windows是否支持此功能;但是select.select ist afaik可用)。 Just have a look at the documentation, the module is in the standard library and well documented (there is no need to know how the OS select() function actually works). 只需看一下文档,该模块就在标准库中并且有很好的文档记录(不需要知道OS select()函数是如何工作的)。
Documentation: https://docs.python.org/3/library/select.html 文档: https : //docs.python.org/3/library/select.html
Note: poll() returns a list of file descriptors, not file-objects. 注意:poll()返回文件描述符列表,而不是文件对象。 So, you should have a dict which maps file descriptors to the corresponding object (I would have this also if I just poll one file. 所以,你应该有一个dict,它将文件描述符映射到相应的对象(如果我只是轮询一个文件,我也会这样做。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.