19.2. Monitoring IO
Prev | Chapter 19. Timeouts, IO and Idle Functions | Next

## 19.2. Monitoring IO

You can check for the ability to read from or write to a file (either a Python file or a lower level OS file) and then automatically invoke a callback. This is especially useful for networking applications. The gobject module function:

      source_id = gobject.io_add_watch(source, condition, callback)

where the first argument (`source`) is the open file (Python file object or lower level file descriptor integer) you wish to have watched. The `gobject.io_add_watch`() function uses the lower level file descriptor integer internally but the function will extract it from the Python file object using the `fileno`() method as needed. The second argument (`condition`) specifies what you want to look for. This may be one of:

      gobject.IO_IN - There is data ready for reading from your file.

      gobject.IO_OUT - The file is ready for writing.

      gobject.IO_PRI - There is urgent data to read.

      gobject.IO_ERR - Error condition.

      gobject.IO_HUP - Hung up (the connection has been broken, usually for
                       pipes and sockets).

These are defined in the gobject module. As I'm sure you've figured out already, the third argument is the `callback` you wish to have called when the above conditions are satisfied.

The return value `source_id` may be used to stop the monitoring of the file by using the following function:

      gobject.source_remove(source_id)

The callback function should be similar to:

      def input_callback(source, condition):

where `source` and `condition` are as specified above. The source value will be the lower level file descriptor integer and not the Python file object (i.e. the value that is returned from the Python file method `fileno`()).

You may also stop the callback function from being called again by returning zero or `FALSE` from your callback. If you want your callback to be called again, it should return `TRUE`.

Prev | Up | Next
Chapter 19. Timeouts, IO and Idle Functions | Home | 19.3. Idle Functions