Reading a named pipe continuously

What's the best way to continuously read a named pipe in 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 like I have a lot of resources from my CPU (one of them will go 100%). It works great with 1 second sleep. However, I need to constantly read the feed to make sure there is new data . Is there a better way to do this?

This is what I am posting to the C ++ pipe:

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

      

Thank!

+3


source to share


1 answer


select.poll works fine (at least for Linux, but not sure if Windows supports this: select.select ist afaik available, though). Just go through the documentation, the module is in the standard library and well documented (no need to know how select () actually works).

Documentation: https://docs.python.org/3/library/select.html



Note. poll () returns a list of file descriptors, not file objects. So you should have a dict file that maps the file descriptors to the corresponding object (I would like to have this as well if I were just polling one file.

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

      

+3


source







All Articles