Skip to content

GLib.IOChannel

record (struct)

The GIOChannel data type aims to provide a portable method for using file descriptors, pipes, and sockets, and integrating them into the main event loop (see MainContext). Currently, full support is available on UNIX platforms; support for Windows is only partially complete.

To create a new GIOChannel on UNIX systems use IOChannel.unix_new. This works for plain file descriptors, pipes and sockets. Alternatively, a channel can be created for a file in a system independent manner using IOChannel.new_file.

Once a GIOChannel has been created, it can be used in a generic manner with the functions IOChannel.read_chars, IOChannel.write_chars, IOChannel.seek_position, and IOChannel.shutdown.

To add a GIOChannel to the main event loop, use io_add_watch or GLib.io_add_watch_full. Here you specify which events you are interested in on the GIOChannel, and provide a function to be called whenever these events occur.

GIOChannel instances are created with an initial reference count of 1. IOChannel.ref and IOChannel.unref can be used to increment or decrement the reference count respectively. When the reference count falls to 0, the GIOChannel is freed. (Though it isn’t closed automatically, unless it was created using IOChannel.new_file.) Using io_add_watch or GLib.io_add_watch_full increments a channel’s reference count.

The new functions IOChannel.read_chars, IOChannel.read_line, IOChannel.read_line_string, IOChannel.read_to_end, IOChannel.write_chars, IOChannel.seek_position, and IOChannel.flush should not be mixed with the deprecated functions IOChannel.read, IOChannel.write, and IOChannel.seek on the same channel.

Constructors

new_file

@classmethod
def new_file(cls, filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: str) -> IOChannel

Open a file filename as a IOChannel using mode mode. This channel will be closed when the last reference to it is dropped, so there is no need to call IOChannel.close (though doing so will not cause problems, as long as no attempt is made to access the channel after it is closed).

Parameters:

  • filename — A string containing the name of a file
  • mode — One of "r", "w", "a", "r+", "w+", "a+". These have the same meaning as in fopen()

unix_new

@classmethod
def unix_new(cls, fd: int) -> IOChannel

Creates a new IOChannel given a file descriptor. On UNIX systems this works for plain files, pipes, and sockets.

The returned IOChannel has a reference count of 1.

The default encoding for IOChannel is UTF-8. If your application is reading output from a command using via pipe, you may need to set the encoding to the encoding of the current locale (see get_charset) with the IOChannel.set_encoding function. By default, the fd passed will not be closed when the final reference to the IOChannel data structure is dropped.

If you want to read raw binary data without interpretation, then call the IOChannel.set_encoding function with None for the encoding argument.

This function is available in GLib on Windows, too, but you should avoid using it on Windows. The domain of file descriptors and sockets overlap. There is no way for GLib to know which one you mean in case the argument you pass to this function happens to be both a valid file descriptor and socket. If that happens a warning is issued, and GLib assumes that it is the file descriptor you mean.

Parameters:

  • fd — a file descriptor.

Methods

close

def close(self) -> None

:::warning Deprecated since 2.2 This API is deprecated. :::

Close an IO channel. Any pending data to be written will be flushed, ignoring errors. The channel will not be freed until the last reference is dropped using IOChannel.unref.

flush

def flush(self) -> IOStatus

Flushes the write buffer for the GIOChannel.

get_buffer_condition

def get_buffer_condition(self) -> IOCondition

This function returns a GObject.IOCondition depending on whether there is data to be read/space to write data in the internal buffers in the IOChannel. Only the flags GObject.IOCondition.IN and GObject.IOCondition.OUT may be set.

get_buffer_size

def get_buffer_size(self) -> int

Gets the buffer size.

get_buffered

def get_buffered(self) -> bool

Returns whether channel is buffered.

get_close_on_unref

def get_close_on_unref(self) -> bool

Returns whether the file/socket/whatever associated with channel will be closed when channel receives its final unref and is destroyed. The default value of this is True for channels created by IOChannel.new_file, and False for all other channels.

get_encoding

def get_encoding(self) -> str

Gets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The encoding None makes the channel safe for binary data.

get_flags

def get_flags(self) -> IOFlags

Gets the current flags for a IOChannel, including read-only flags such as IOFlags.IS_READABLE.

The values of the flags IOFlags.IS_READABLE and IOFlags.IS_WRITABLE are cached for internal use by the channel when it is created. If they should change at some later point (e.g. partial shutdown of a socket with the UNIX shutdown() function), the user should immediately call IOChannel.get_flags to update the internal values of these flags.

get_line_term

def get_line_term(self) -> tuple[str, int]

This returns the string that IOChannel uses to determine where in the file a line break occurs. A value of None indicates autodetection. Since 2.84, the return value is always nul-terminated.

init

def init(self) -> None

Initializes a IOChannel struct.

This is called by each of the above functions when creating a IOChannel, and so is not often needed by the application programmer (unless you are creating a new type of IOChannel).

read

def read(self, buf: str, count: int, bytes_read: int) -> IOError

:::warning Deprecated since 2.2 This API is deprecated. :::

Reads data from a IOChannel.

Parameters:

  • buf — a buffer to read the data into (which should be at least count bytes long)
  • count — the number of bytes to read from the IOChannel
  • bytes_read — returns the number of bytes actually read

read_chars

def read_chars(self) -> tuple[IOStatus, list[int], int]

Replacement for IOChannel.read with the new API.

read_line

def read_line(self) -> tuple[IOStatus, str, int, int]

Reads a line, including the terminating character(s), from a IOChannel into a newly-allocated string. str_return will contain allocated memory if the return is IOStatus.NORMAL.

read_line_string

def read_line_string(self, buffer: String, terminator_pos: int | None = ...) -> IOStatus

Reads a line from a IOChannel, using a String as a buffer.

Parameters:

  • buffer — a String into which the line will be written. If buffer already contains data, the old data will be overwritten.
  • terminator_pos — location to store position of line terminator, or None

read_to_end

def read_to_end(self) -> tuple[IOStatus, list[int]]

Reads all the remaining data from the file.

read_unichar

def read_unichar(self) -> tuple[IOStatus, str]

Reads a Unicode character from channel. This function cannot be called on a channel with None encoding.

ref

def ref(self) -> IOChannel

Increments the reference count of a IOChannel.

seek

def seek(self, offset: int, type: SeekType | int) -> IOError

:::warning Deprecated since 2.2 This API is deprecated. :::

Sets the current position in the IOChannel, similar to the standard library function fseek().

Parameters:

  • offset — an offset, in bytes, which is added to the position specified by type
  • type — the position in the file, which can be SeekType.CUR (the current position), SeekType.SET (the start of the file), or SeekType.END (the end of the file)

seek_position

def seek_position(self, offset: int, type: SeekType | int) -> IOStatus

Replacement for IOChannel.seek with the new API.

Parameters:

set_buffer_size

def set_buffer_size(self, size: int) -> None

Sets the buffer size.

Parameters:

  • size — the size of the buffer, or 0 to let GLib pick a good size

set_buffered

def set_buffered(self, buffered: bool) -> None

The buffering state can only be set if the channel's encoding is None. For any other encoding, the channel must be buffered.

A buffered channel can only be set unbuffered if the channel's internal buffers have been flushed. Newly created channels or channels which have returned IOStatus.EOF not require such a flush. For write-only channels, a call to IOChannel.flush is sufficient. For all other channels, the buffers may be flushed by a call to IOChannel.seek_position. This includes the possibility of seeking with seek type SeekType.CUR and an offset of zero. Note that this means that socket-based channels cannot be set unbuffered once they have had data read from them.

On unbuffered channels, it is safe to mix read and write calls from the new and old APIs, if this is necessary for maintaining old code.

The default state of the channel is buffered.

Parameters:

  • buffered — whether to set the channel buffered or unbuffered

set_close_on_unref

def set_close_on_unref(self, do_close: bool) -> None

Whether to close the channel on the final unref of the IOChannel data structure. The default value of this is True for channels created by IOChannel.new_file, and False for all other channels.

Setting this flag to True for a channel you have already closed can cause problems when the final reference to the IOChannel is dropped.

Parameters:

  • do_close — Whether to close the channel on the final unref of the GIOChannel data structure.

set_encoding

def set_encoding(self, encoding: str | None = ...) -> IOStatus

Sets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The default encoding for the external file is UTF-8.

The encoding None is safe to use with binary data.

The encoding can only be set if one of the following conditions is true:

Channels which do not meet one of the above conditions cannot call IOChannel.seek_position with an offset of SeekType.CUR, and, if they are "seekable", cannot call IOChannel.write_chars after calling one of the API "read" functions.

Parameters:

  • encoding — the encoding type

set_flags

def set_flags(self, flags: IOFlags | int) -> IOStatus

Sets the (writeable) flags in channel to (flags & IOFlags.SET_MASK).

Parameters:

  • flags — the flags to set on the IO channel

set_line_term

def set_line_term(self, line_term: str | None, length: int) -> None

This sets the string that IOChannel uses to determine where in the file a line break occurs.

Parameters:

  • line_term — The line termination string. Use None for autodetect. Autodetection breaks on "\n", "\r\n", "\r", "\0", and the Unicode paragraph separator. Autodetection should not be used for anything other than file-based channels.
  • length — The length of the termination string. If -1 is passed, the string is assumed to be nul-terminated. This option allows termination strings with embedded nuls.

shutdown

def shutdown(self, flush: bool) -> IOStatus

Close an IO channel. Any pending data to be written will be flushed if flush is True. The channel will not be freed until the last reference is dropped using IOChannel.unref.

Parameters:

  • flush — if True, flush pending

unix_get_fd

def unix_get_fd(self) -> int

Returns the file descriptor of the IOChannel.

On Windows this function returns the file descriptor or socket of the IOChannel.

unref

def unref(self) -> None

Decrements the reference count of a IOChannel.

write

def write(self, buf: str, count: int, bytes_written: int) -> IOError

:::warning Deprecated since 2.2 This API is deprecated. :::

Writes data to a IOChannel.

Parameters:

  • buf — the buffer containing the data to write
  • count — the number of bytes to write
  • bytes_written — the number of bytes actually written

write_chars

def write_chars(self, buf: list[int], count: int) -> tuple[IOStatus, int]

Replacement for IOChannel.write with the new API.

On seekable channels with encodings other than None or UTF-8, generic mixing of reading and writing is not allowed. A call to IOChannel.write_chars may only be made on a channel from which data has been read in the cases described in the documentation for IOChannel.set_encoding.

Parameters:

  • buf — a buffer to write data from
  • count — the size of the buffer. If -1, the buffer is taken to be a nul-terminated string.

write_unichar

def write_unichar(self, thechar: str) -> IOStatus

Writes a Unicode character to channel. This function cannot be called on a channel with None encoding.

Parameters:

  • thechar — a character

Static functions

error_from_errno

@staticmethod
def error_from_errno(en: int) -> IOChannelError

Converts an errno error number to a IOChannelError.

Parameters:

  • en — an errno error number, e.g. EINVAL

error_quark

@staticmethod
def error_quark() -> Quark

Properties

ref_count

ref_count: int  # read/write

funcs

funcs: IOFuncs  # read/write

encoding

encoding: str  # read/write

line_term

line_term: str  # read/write

line_term_len

line_term_len: int  # read/write

buf_size

buf_size: int  # read/write

read_buf

read_buf: String  # read/write

encoded_read_buf

encoded_read_buf: String  # read/write

write_buf

write_buf: String  # read/write

partial_write_buf

partial_write_buf: list[int]  # read/write

use_buffer

use_buffer: int  # read/write

do_encode

do_encode: int  # read/write

close_on_unref

close_on_unref: int  # read/write

is_readable

is_readable: int  # read/write

is_writeable

is_writeable: int  # read/write

is_seekable

is_seekable: int  # read/write

reserved1

reserved1: int  # read/write

reserved2

reserved2: int  # read/write