GLib¶
API reference for the GLib namespace (version 2.0), generated from GObject-Introspection.
Classes¶
- Allocator
- Array — Contains the public fields of a
GArray. - AsyncQueue — An opaque data structure which represents an asynchronous queue. It should only be accessed through the
g_async_queue_*functions. - BookmarkFile —
GBookmarkFilelets you parse, edit or create files containing bookmarks. Bookmarks refer to a URI, along with some meta-data about the… - ByteArray — Contains the public fields of a
GByteArray. - Bytes — A simple reference counted data type representing an immutable sequence of zero or more bytes from an unspecified origin. The purpose of a…
- Cache — A
GCacheallows sharing of complex data structures, in order to save system resources.GCacheuses keys and values. AGCachekey… - Checksum — GLib provides a generic API for computing checksums (or ‘digests’) for a sequence of arbitrary bytes, using various hashing algorithms like…
- Completion —
GCompletionprovides support for automatic completion of a string using any group of target strings. It is typically used for file name… - Cond — The Cond struct is an opaque data structure that represents a condition. Threads can block on a Cond if they find a certain condition to be…
- Data — An opaque data structure that represents a keyed data list. See also: Keyed data lists.
- Date —
GDateis a struct for calendrical calculations. TheGDatedata structure represents a day between January 1, Year 1, and sometime a few… - DateTime —
GDateTimeis a structure that combines a Gregorian date and time into a single structure.GDateTimeprovides many conversion and… - DebugKey — Associates a string with a bit flag. Used in parse_debug_string.
- Dir — An opaque structure representing an opened directory.
- DoubleIEEE754 — The FloatIEEE754 and DoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are…
- Error — The
GErrorstructure contains information about an error that has occurred. - FloatIEEE754 — The FloatIEEE754 and DoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are…
- HashTable — The HashTable struct is an opaque data structure to represent a Hash Table. It should only be accessed via the following functions.
- HashTableIter — A GHashTableIter structure represents an iterator that can be used to iterate over the elements of a HashTable. GHashTableIter structures…
- Hmac — HMACs should be used when producing a cookie or hash based on data and a key. Simple mechanisms for using SHA1 and other algorithms to…
- Hook — The Hook struct represents a single hook function in a HookList.
- HookList — The HookList struct represents a list of hook functions.
- IOChannel — The
GIOChanneldata type aims to provide a portable method for using file descriptors, pipes, and sockets, and integrating them into the… - IOFuncs — A table of functions used to handle different types of IOChannel in a generic way.
- KeyFile —
GKeyFileparses .ini-like config files.GKeyFilelets you parse, edit or create files containing groups of key-value pairs, which we… - List — The List struct is used for each element in a doubly-linked list.
- LogField — Structure representing a single field in a structured log entry. See g_log_structured() for details. Log fields may contain arbitrary…
- MainContext — The
GMainContextstruct is an opaque data type representing a set of sources to be handled in a main loop. - MainLoop — The
GMainLoopstruct is an opaque data type representing the main event loop of a GLib or GTK application. - MappedFile — The MappedFile represents a file mapping created with MappedFile.new. It has only private members and should not be accessed directly.
- MarkupParseContext — A parse context is used to parse a stream of bytes that you expect to contain marked-up text. See MarkupParseContext.new, MarkupParser, and…
- MarkupParser — Any of the fields in MarkupParser can be
None, in which case they will be ignored. Except for theerrorfunction, any of these… - MatchInfo — A GMatchInfo is an opaque struct used to return information about matches.
- MemChunk
- MemVTable — A set of functions used to perform memory allocation. The same MemVTable must be used for all allocations in the same program; a call to…
- Mutex — The Mutex struct is an opaque data structure to represent a mutex (mutual exclusion). It can be used to protect data against shared access.…
- Node — The Node struct represents one node in a n-ary tree.
- Once — A Once struct controls a one-time initialization function. Any one-time initialization function must have its own unique Once struct.
- OptionContext — A
GOptionContextstruct defines which options are accepted by the commandline option parser. The struct has only private fields and… - OptionEntry — - OptionArg.NONE:
gboolean- OptionArg.STRING:gchar- OptionArg.INT:gint- OptionArg.FILENAME:gchar- OptionArg.STRING_ARRAY:… - OptionGroup — A
GOptionGroupstruct defines the options in a single group. The struct has only private fields and should not be directly accessed. All… - PathBuf —
GPathBufis a helper type that allows you to easily build paths from individual elements, using the platform specific conventions for… - PatternSpec — A
GPatternSpecstruct is the ‘compiled’ form of a glob-style pattern. The pattern_match_simple and PatternSpec.match functions match a… - PollFD — Represents a file descriptor, which events to poll for, and which events occurred.
- Private — The Private struct is an opaque data structure to represent a thread-local data key. It is approximately equivalent to the…
- PtrArray — Contains the public fields of a
GPtrArray. - Queue — Contains the public fields of a Queue.
- RWLock — The GRWLock struct is an opaque data structure to represent a reader-writer lock. It is similar to a Mutex in that it allows multiple…
- Rand — The GRand struct is an opaque data structure. It should only be accessed through the g_rand_* functions.
- RecMutex — The GRecMutex struct is an opaque data structure to represent a recursive mutex. It is similar to a Mutex with the difference that it is…
- Regex — A
GRegexis a compiled form of a regular expression. After instantiating aGRegex, you can use its methods to find matches in a string,… - Relation — A
GRelationis a table of data which can be indexed on any number of fields, rather like simple database tables. AGRelationcontains a… - SList — The SList struct is used for each element in the singly-linked list.
- Scanner —
GScannerprovides a general-purpose lexical scanner. You should setinput_nameafter creating the scanner, since it is used by the… - ScannerConfig — Specifies the Scanner parser configuration. Most settings can be changed during the parsing phase and will affect the lexical parsing of…
- Sequence — The Sequence struct is an opaque data type representing a sequence data type.
- SequenceIter — The SequenceIter struct is an opaque data type representing an iterator pointing into a Sequence.
- Source — The
GSourcestruct is an opaque data type representing an event source. - SourceCallbackFuncs — The
GSourceCallbackFuncsstruct contains functions for managing callback objects. - SourceFuncs — The
GSourceFuncsstruct contains a table of functions used to handle event sources in a generic manner. For idle sources, the prepare and… - SourcePrivate
- StatBuf — A type corresponding to the appropriate struct type for the stat() system call, depending on the platform and/or compiler being used. See…
- String — A
GStringis an object that handles the memory management of a C string. The emphasis ofGStringis on text, typically UTF-8.… - StringChunk —
GStringChunkprovides efficient storage of groups of strings String chunks are used to store groups of strings. Memory is allocated in… - StrvBuilder —
GStrvBuilderis a helper object to build aNone-terminated string arrays. The following example shows how to build a two element array:… - TestCase — An opaque structure representing a test case.
- TestConfig
- TestLogBuffer
- TestLogMsg
- TestSuite — An opaque structure representing a test suite.
- Thread — The Thread struct represents a running thread. This struct is returned by Thread.new or Thread.try_new. You can obtain the Thread struct…
- ThreadPool — The
GThreadPoolstruct represents a thread pool. A thread pool is useful when you wish to asynchronously fork out the execution of work… - TimeVal — Represents a precise time, with seconds and microseconds. Similar to the struct timeval returned by the
gettimeofday()UNIX system call.… - TimeZone — A
GTimeZonerepresents a time zone, at no particular point in time. TheGTimeZonestruct is refcounted and immutable. Each time zone… - Timer —
GTimerrecords a start time, and counts microseconds elapsed since that time. This is done somewhat differently on different platforms,… - TokenValue — A union holding the value of the token.
- TrashStack — A
GTrashStackis an efficient way to keep a stack of unused allocated memory chunks. Each memory chunk is required to be large enough to… - Tree — The GTree struct is an opaque data structure representing a balanced binary tree. It should be accessed only by using the following…
- TreeNode — An opaque type which identifies a specific node in a Tree.
- Tuples — The Tuples struct is used to return records (or tuples) from the Relation by g_relation_select(). It only contains one public member - the…
- Uri — The
GUritype and related functions can be used to parse URIs into their components, and build valid URIs from individual components.… - UriParamsIter — Many URI schemes include one or more attribute/value pairs as part of the URI value. For example…
- Variant —
GVariantis a variant datatype; it can contain one or more values along with information about the type of the values. AGVariantmay… - VariantBuilder — A utility type for constructing container-type Variant instances. This is an opaque structure and may only be accessed using the following…
- VariantDict — VariantDict is a mutable interface to Variant dictionaries. It can be used for doing a sequence of dictionary lookups in an efficient way…
- VariantType — A type in the Variant type system. Variant types are represented as strings, but have a strict syntax described below. All VariantTypes…
Functions¶
access¶
A wrapper for the POSIX access() function. This function is used to test a pathname for one or several of read, write or execute permissions, or just existence.
On Windows, the file protection mechanism is not at all POSIX-like, and the underlying function in the C library only checks the FAT-style READONLY attribute, and does not look at the ACL of a file at all. This function is this in practise almost useless on Windows. Software that needs to handle file permissions on Windows more exactly should use the Win32 API.
See your C library manual for more details about access().
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)mode— as in access()
aligned_alloc¶
This function is similar to malloc, allocating (n_blocks * n_block_bytes)
bytes, but care is taken to align the allocated memory to with the given
alignment value. Additionally, it will detect possible overflow during
multiplication.
If the allocation fails (because the system is out of memory), the program is terminated.
Aligned memory allocations returned by this function can only be
freed using aligned_free_sized or aligned_free.
Parameters:
n_blocks— the number of blocks to allocaten_block_bytes— the size of each block in bytesalignment— the alignment to be enforced, which must be a positive power of 2 and a multiple ofsizeof(void*)
aligned_alloc0¶
This function is similar to aligned_alloc, but it will
also clear the allocated memory before returning it.
Parameters:
n_blocks— the number of blocks to allocaten_block_bytes— the size of each block in bytesalignment— the alignment to be enforced, which must be a positive power of 2 and a multiple ofsizeof(void*)
aligned_free¶
Frees the memory allocated by aligned_alloc.
Parameters:
mem— the memory to deallocate
aligned_free_sized¶
Frees the memory pointed to by mem, assuming it is has the given size and
alignment.
If mem is None this is a no-op (and size is ignored).
It is an error if size doesn’t match the size, or alignment doesn’t match
the alignment, passed when mem was allocated. size and alignment are
passed to this function to allow optimizations in the allocator. If you
don’t know either of them, use aligned_free instead.
Parameters:
mem— the memory to freealignment— alignment ofmemsize— size ofmem, in bytes
ascii_digit_value¶
Determines the numeric value of a character as a decimal digit. If the
character is not a decimal digit according to GLib.ascii_isdigit,
-1 is returned.
Differs from unichar_digit_value because it takes a char, so
there's no worry about sign extension if characters are signed.
Parameters:
c— an ASCII character
ascii_dtostr¶
Converts a gdouble to a string, using the '.' as
decimal point.
This function generates enough precision that converting
the string back using ascii_strtod gives the same machine-number
(on machines with IEEE compatible 64bit doubles). It is
guaranteed that the size of the resulting string will never
be larger than ASCII_DTOSTR_BUF_SIZE bytes, including the terminating
nul character, which is always added.
Parameters:
buffer— a buffer to place the resulting string inbuf_len— the length of the bufferd— the value to convert
ascii_formatd¶
Converts a gdouble to a string, using the '.' as
decimal point. To format the number you pass in
a printf()-style format string. Allowed conversion
specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.
The format must just be a single format specifier
starting with %, expecting a gdouble argument.
The returned buffer is guaranteed to be nul-terminated.
If you just want to want to serialize the value into a
string, use ascii_dtostr.
Parameters:
buffer— a buffer to place the resulting string inbuf_len— the length of the bufferformat— theprintf()-style format to use for the code to use for convertingd— the value to convert
ascii_strcasecmp¶
Compare two strings, ignoring the case of ASCII characters.
Unlike the BSD strcasecmp() function, this only recognizes standard
ASCII letters and ignores the locale, treating all non-ASCII
bytes as if they are not letters.
This function should be used only on strings that are known to be in encodings where the bytes corresponding to ASCII letters always represent themselves. This includes UTF-8 and the ISO-8859-* charsets, but not for instance double-byte encodings like the Windows Codepage 932, where the trailing bytes of double-byte characters include all ASCII letters. If you compare two CP932 strings using this function, you will get false matches.
Both s1 and s2 must be non-NULL.
Parameters:
s1— string to compare withs2s2— string to compare withs1
ascii_strdown¶
Converts all upper case ASCII letters to lower case ASCII letters, with
semantics that exactly match ascii_tolower.
Parameters:
str— a stringlen— length ofstrin bytes, or-1ifstris nul-terminated
ascii_string_to_signed¶
A convenience function for converting a string to a signed number.
This function assumes that str contains only a number of the given
base that is within inclusive bounds limited by min and max. If
this is true, then the converted number is stored in out_num. An
empty string is not a valid input. A string with leading or
trailing whitespace is also an invalid input.
base can be between 2 and 36 inclusive. Hexadecimal numbers must
not be prefixed with "0x" or "0X". Such a problem does not exist
for octal numbers, since they were usually prefixed with a zero
which does not change the value of the parsed number.
Parsing failures result in an error with the G_NUMBER_PARSER_ERROR
domain. If the input is invalid, the error code will be
NumberParserError.INVALID. If the parsed number is out of
bounds - NumberParserError.OUT_OF_BOUNDS.
See ascii_strtoll if you have more complex needs such as
parsing a string which starts with a number, but then has other
characters.
Parameters:
str— a string to convertbase— base of a parsed numbermin— a lower bound (inclusive)max— an upper bound (inclusive)
ascii_string_to_unsigned¶
A convenience function for converting a string to an unsigned number.
This function assumes that str contains only a number of the given
base that is within inclusive bounds limited by min and max. If
this is true, then the converted number is stored in out_num. An
empty string is not a valid input. A string with leading or
trailing whitespace is also an invalid input. A string with a leading sign
(- or +) is not a valid input for the unsigned parser.
base can be between 2 and 36 inclusive. Hexadecimal numbers must
not be prefixed with "0x" or "0X". Such a problem does not exist
for octal numbers, since they were usually prefixed with a zero
which does not change the value of the parsed number.
Parsing failures result in an error with the G_NUMBER_PARSER_ERROR
domain. If the input is invalid, the error code will be
NumberParserError.INVALID. If the parsed number is out of
bounds - NumberParserError.OUT_OF_BOUNDS.
See ascii_strtoull if you have more complex needs such as
parsing a string which starts with a number, but then has other
characters.
Parameters:
str— a stringbase— base of a parsed numbermin— a lower bound (inclusive)max— an upper bound (inclusive)
ascii_strncasecmp¶
Compare s1 and s2, ignoring the case of ASCII characters and any
characters after the first n in each string. If either string is
less than n bytes long, comparison will stop at the first nul byte
encountered.
Unlike the BSD strncasecmp() function, this only recognizes standard
ASCII letters and ignores the locale, treating all non-ASCII
characters as if they are not letters.
The same warning as in ascii_strcasecmp applies: Use this
function only on strings known to be in encodings where bytes
corresponding to ASCII letters always represent themselves.
Parameters:
s1— string to compare withs2s2— string to compare withs1n— number of characters to compare
ascii_strtod¶
Converts a string to a floating point value.
This function behaves like the standard strtod() function
does in the C locale. It does this without actually changing
the current locale, since that would not be thread-safe.
A limitation of the implementation is that this function
will still accept localized versions of infinities and NANs.
This function is typically used when reading configuration
files or other non-user input that should be locale independent.
To handle input from the user you should normally use the
locale-sensitive system strtod() function.
To convert from a gdouble to a string in a locale-insensitive
way, use ascii_dtostr.
If the correct value would cause overflow, plus or minus HUGE_VAL
is returned (according to the sign of the value), and ERANGE is
stored in errno. If the correct value would cause underflow,
zero is returned and ERANGE is stored in errno.
This function resets errno before calling strtod() so that
you can reliably detect overflow and underflow.
Parameters:
nptr— the string to convert to a numeric value
ascii_strtoll¶
Converts a string to a gint64 value.
This function behaves like the standard strtoll() function
does in the C locale. It does this without actually
changing the current locale, since that would not be
thread-safe.
This function is typically used when reading configuration
files or other non-user input that should be locale independent.
To handle input from the user you should normally use the
locale-sensitive system strtoll() function.
If the correct value would cause overflow, MAXINT64 or
MININT64 is returned, and ERANGE is stored in errno.
If the base is outside the valid range, zero is returned, and
EINVAL is stored in errno. If the
string conversion fails, zero is returned, and endptr returns nptr
(if endptr is non-NULL).
Parameters:
nptr— the string to convert to a numeric valuebase— to be used for the conversion, 2..36 or 0
ascii_strtoull¶
Converts a string to a guint64 value.
This function behaves like the standard strtoull() function
does in the C locale. It does this without actually
changing the current locale, since that would not be
thread-safe.
Note that input with a leading minus sign (-) is accepted, and will return
the negation of the parsed number, unless that would overflow a guint64.
Critically, this means you cannot assume that a short fixed length input will
result in a low return value, as the input could have a leading -.
This function is typically used when reading configuration
files or other non-user input that should be locale independent.
To handle input from the user you should normally use the
locale-sensitive system strtoull() function.
If the correct value would cause overflow, MAXUINT64
is returned, and ERANGE is stored in errno.
If the base is outside the valid range, zero is returned, and
EINVAL is stored in errno.
If the string conversion fails, zero is returned, and endptr returns
nptr (if endptr is non-NULL).
Parameters:
nptr— the string to convert to a numeric valuebase— to be used for the conversion, 2..36 or 0
ascii_strup¶
Converts all lower case ASCII letters to upper case ASCII letters, with
semantics that exactly match ascii_toupper.
Parameters:
str— a stringlen— length ofstrin bytes, or-1ifstris nul-terminated
ascii_tolower¶
Convert a character to ASCII lower case. If the character is not an ASCII upper case letter, it is returned unchanged.
Unlike the standard C library tolower() function, this only
recognizes standard ASCII letters and ignores the locale, returning
all non-ASCII characters unchanged, even if they are lower case
letters in a particular character set. Also unlike the standard
library function, this takes and returns a char, not an int, so
don't call it on EOF but no need to worry about casting to guchar
before passing a possibly non-ASCII character in.
Parameters:
c— any character
ascii_toupper¶
Convert a character to ASCII upper case. If the character is not an ASCII lower case letter, it is returned unchanged.
Unlike the standard C library toupper() function, this only
recognizes standard ASCII letters and ignores the locale, returning
all non-ASCII characters unchanged, even if they are upper case
letters in a particular character set. Also unlike the standard
library function, this takes and returns a char, not an int, so
don't call it on EOF but no need to worry about casting to guchar
before passing a possibly non-ASCII character in.
Parameters:
c— any character
ascii_xdigit_value¶
Determines the numeric value of a character as a hexadecimal digit. If the
character is not a hex digit according to GLib.ascii_isxdigit,
-1 is returned.
Differs from unichar_xdigit_value because it takes a char, so
there's no worry about sign extension if characters are signed.
Differs from unichar_xdigit_value because it takes a char, so
there's no worry about sign extension if characters are signed.
Parameters:
c— an ASCII character
assert_warning¶
def assert_warning(log_domain: str, file: str, line: int, pretty_function: str, expression: str) -> None
assertion_message¶
assertion_message_cmpint¶
def assertion_message_cmpint(domain: str, file: str, line: int, func: str, expr: str, arg1: int, cmp: str, arg2: int, numtype: int) -> None
assertion_message_cmpstr¶
def assertion_message_cmpstr(domain: str, file: str, line: int, func: str, expr: str, arg1: str, cmp: str, arg2: str) -> None
assertion_message_cmpstrv¶
def assertion_message_cmpstrv(domain: str, file: str, line: int, func: str, expr: str, arg1: str, arg2: str, first_wrong_idx: int) -> None
assertion_message_error¶
def assertion_message_error(domain: str, file: str, line: int, func: str, expr: str, error: Error, error_domain: Quark, error_code: int) -> None
atexit¶
:::warning Deprecated since 2.32 This API is deprecated. :::
Specifies a function to be called at normal program termination.
Since GLib 2.8.2, on Windows atexit actually is a preprocessor
macro that maps to a call to the atexit() function in the C
library. This means that in case the code that calls atexit,
i.e. atexit(), is in a DLL, the function will be called when the
DLL is detached from the program. This typically makes more sense
than that the function is called when the GLib DLL is detached,
which happened earlier when atexit was a function in the GLib
DLL.
The behaviour of atexit() in the context of dynamically loaded modules is not formally specified and varies wildly.
On POSIX systems, calling atexit (or atexit()) in a dynamically
loaded module which is unloaded before the program terminates might
well cause a crash at program exit.
Some POSIX systems implement atexit() like Windows, and have each dynamically loaded module maintain an own atexit chain that is called when the module is unloaded.
On other POSIX systems, before a dynamically loaded module is unloaded, the registered atexit functions (if any) residing in that module are called, regardless where the code that registered them resided. This is presumably the most robust approach.
As can be seen from the above, for portability it's best to avoid
calling atexit (or atexit()) except in the main executable of a
program.
Parameters:
func— the function to call on normal program termination.
atomic_int_add¶
Atomically adds val to the value of atomic.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic += val; return tmp; }.
This call acts as a full compiler and hardware memory barrier.
Before version 2.30, this function did not return a value
(but atomic_int_exchange_and_add did, and had the same meaning).
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gint or #guintval— the value to add
atomic_int_and¶
Performs an atomic bitwise 'and' of the value of atomic and val,
storing the result back in atomic.
This call acts as a full compiler and hardware memory barrier.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic &= val; return tmp; }.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gint or #guintval— the value to 'and'
atomic_int_compare_and_exchange¶
Compares atomic to oldval and, if equal, sets it to newval.
If atomic was not equal to oldval then no change occurs.
This compare and exchange is done atomically.
Think of this operation as an atomic version of
{ if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gint or #guintoldval— the value to compare withnewval— the value to conditionally replace with
atomic_int_compare_and_exchange_full¶
def atomic_int_compare_and_exchange_full(atomic: int | None, oldval: int, newval: int) -> tuple[bool, int]
Compares atomic to oldval and, if equal, sets it to newval.
If atomic was not equal to oldval then no change occurs.
In any case the value of atomic before this operation is stored in preval.
This compare and exchange is done atomically.
Think of this operation as an atomic version of
{ *preval = *atomic; if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.
This call acts as a full compiler and hardware memory barrier.
See also atomic_int_compare_and_exchange
Parameters:
atomic— a pointer to a #gint or #guintoldval— the value to compare withnewval— the value to conditionally replace with
atomic_int_dec_and_test¶
Decrements the value of atomic by 1.
Think of this operation as an atomic version of
{ *atomic -= 1; return (*atomic == 0); }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gint or #guint
atomic_int_exchange¶
Sets the atomic to newval and returns the old value from atomic.
This exchange is done atomically.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic = val; return tmp; }.
This call acts as a full compiler and hardware memory barrier.
Parameters:
atomic— a pointer to a #gint or #guintnewval— the value to replace with
atomic_int_exchange_and_add¶
:::warning Deprecated since 2.30 This API is deprecated. :::
This function existed before atomic_int_add returned the prior
value of the integer (which it now does). It is retained only for
compatibility reasons. Don't use this function in new code.
Parameters:
atomic— a pointer to a #gintval— the value to add
atomic_int_get¶
Gets the current value of atomic.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gint or #guint
atomic_int_inc¶
Increments the value of atomic by 1.
Think of this operation as an atomic version of { *atomic += 1; }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gint or #guint
atomic_int_or¶
Performs an atomic bitwise 'or' of the value of atomic and val,
storing the result back in atomic.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic |= val; return tmp; }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gint or #guintval— the value to 'or'
atomic_int_set¶
Sets the value of atomic to newval.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gint or #guintnewval— a new value to store
atomic_int_xor¶
Performs an atomic bitwise 'xor' of the value of atomic and val,
storing the result back in atomic.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic ^= val; return tmp; }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gint or #guintval— the value to 'xor'
atomic_pointer_add¶
Atomically adds val to the value of atomic.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic += val; return tmp; }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
In GLib 2.80, the return type was changed from #gssize to #gintptr to add support for platforms with 128-bit pointers. This should not affect existing code.
Parameters:
atomic— a pointer to a #gpointer-sized valueval— the value to add
atomic_pointer_and¶
Performs an atomic bitwise 'and' of the value of atomic and val,
storing the result back in atomic.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic &= val; return tmp; }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
In GLib 2.80, the return type was changed from #gsize to #guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.
Parameters:
atomic— a pointer to a #gpointer-sized valueval— the value to 'and'
atomic_pointer_compare_and_exchange¶
def atomic_pointer_compare_and_exchange(atomic: int, oldval: int | None = ..., newval: int | None = ...) -> bool
Compares atomic to oldval and, if equal, sets it to newval.
If atomic was not equal to oldval then no change occurs.
This compare and exchange is done atomically.
Think of this operation as an atomic version of
{ if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gpointer-sized valueoldval— the value to compare withnewval— the value to conditionally replace with
atomic_pointer_compare_and_exchange_full¶
def atomic_pointer_compare_and_exchange_full(atomic: int, oldval: int | None = ..., newval: int | None = ...) -> tuple[bool, int]
Compares atomic to oldval and, if equal, sets it to newval.
If atomic was not equal to oldval then no change occurs.
In any case the value of atomic before this operation is stored in preval.
This compare and exchange is done atomically.
Think of this operation as an atomic version of
{ *preval = *atomic; if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.
This call acts as a full compiler and hardware memory barrier.
See also atomic_pointer_compare_and_exchange
Parameters:
atomic— a pointer to a #gpointer-sized valueoldval— the value to compare withnewval— the value to conditionally replace with
atomic_pointer_exchange¶
Sets the atomic to newval and returns the old value from atomic.
This exchange is done atomically.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic = val; return tmp; }.
This call acts as a full compiler and hardware memory barrier.
Parameters:
atomic— a pointer to a #gpointer-sized valuenewval— the value to replace with
atomic_pointer_get¶
Gets the current value of atomic.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gpointer-sized value
atomic_pointer_or¶
Performs an atomic bitwise 'or' of the value of atomic and val,
storing the result back in atomic.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic |= val; return tmp; }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
In GLib 2.80, the return type was changed from #gsize to #guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.
Parameters:
atomic— a pointer to a #gpointer-sized valueval— the value to 'or'
atomic_pointer_set¶
Sets the value of atomic to newval.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
Parameters:
atomic— a pointer to a #gpointer-sized valuenewval— a new value to store
atomic_pointer_xor¶
Performs an atomic bitwise 'xor' of the value of atomic and val,
storing the result back in atomic.
Think of this operation as an atomic version of
{ tmp = *atomic; *atomic ^= val; return tmp; }.
This call acts as a full compiler and hardware memory barrier.
While atomic has a volatile qualifier, this is a historical artifact and
the pointer passed to it should not be volatile.
In GLib 2.80, the return type was changed from #gsize to #guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.
Parameters:
atomic— a pointer to a #gpointer-sized valueval— the value to 'xor'
atomic_rc_box_acquire¶
Atomically acquires a reference on the data pointed by mem_block.
Parameters:
mem_block— a pointer to reference counted data
atomic_rc_box_alloc¶
Allocates block_size bytes of memory, and adds atomic
reference counting semantics to it.
The data will be freed when its reference count drops to zero.
The allocated data is guaranteed to be suitably aligned for any built-in type.
Parameters:
block_size— the size of the allocation, must be greater than 0
atomic_rc_box_alloc0¶
Allocates block_size bytes of memory, and adds atomic
reference counting semantics to it.
The contents of the returned data is set to zero.
The data will be freed when its reference count drops to zero.
The allocated data is guaranteed to be suitably aligned for any built-in type.
Parameters:
block_size— the size of the allocation, must be greater than 0
atomic_rc_box_dup¶
Allocates a new block of data with atomic reference counting
semantics, and copies block_size bytes of mem_block
into it.
Parameters:
block_size— the number of bytes to copy, must be greater than 0mem_block— the memory to copy
atomic_rc_box_get_size¶
Retrieves the size of the reference counted data pointed by mem_block.
Parameters:
mem_block— a pointer to reference counted data
atomic_rc_box_release¶
Atomically releases a reference on the data pointed by mem_block.
If the reference was the last one, it will free the
resources allocated for mem_block.
Parameters:
mem_block— a pointer to reference counted data
atomic_rc_box_release_full¶
Atomically releases a reference on the data pointed by mem_block.
If the reference was the last one, it will call clear_func
to clear the contents of mem_block, and then will free the
resources allocated for mem_block.
Note that implementing weak references via clear_func is not thread-safe:
clearing a pointer to the memory from the callback can race with another
thread trying to access it as mem_block already has a reference count of 0
when the callback is called and will be freed.
Parameters:
mem_block— a pointer to reference counted dataclear_func— a function to call when clearing the data
atomic_ref_count_compare¶
Atomically compares the current value of arc with val.
Parameters:
arc— the address of an atomic reference count variableval— the value to compare
atomic_ref_count_dec¶
Atomically decreases the reference count.
If True is returned, the reference count reached 0. After this point, arc
is an undefined state and must be reinitialized with
atomic_ref_count_init to be used again.
Parameters:
arc— the address of an atomic reference count variable
atomic_ref_count_inc¶
Atomically increases the reference count.
Parameters:
arc— the address of an atomic reference count variable
atomic_ref_count_init¶
Initializes a reference count variable to 1.
base64_decode¶
Decode a sequence of Base-64 encoded text into binary data. Note that the returned binary data is not necessarily zero-terminated, so it should not be used as a character string.
Parameters:
text— zero-terminated string with base64 text to decode
base64_decode_inplace¶
Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.
Parameters:
text— zero-terminated string with base64 text to decode
base64_encode¶
Encode a sequence of binary data into its Base-64 stringified representation.
Parameters:
data— the binary data to encode
base64_encode_close¶
def base64_encode_close(break_lines: bool, state: int, save: int) -> tuple[int, list[int], int, int]
Flush the status from a sequence of calls to base64_encode_step.
The output buffer must be large enough to fit all the data that will be written to it. It will need up to 4 bytes, or up to 5 bytes if line-breaking is enabled.
The out array will not be automatically nul-terminated.
Parameters:
break_lines— whether to break long linesstate— Saved state frombase64_encode_stepsave— Saved state frombase64_encode_step
base64_encode_step¶
def base64_encode_step(in_: list[int], break_lines: bool, state: int, save: int) -> tuple[int, list[int], int, int]
Incrementally encode a sequence of binary data into its Base-64 stringified representation. By calling this function multiple times you can convert data in chunks to avoid having to have the full encoded data in memory.
When all of the data has been converted you must call
base64_encode_close to flush the saved state.
The output buffer must be large enough to fit all the data that will
be written to it. Due to the way base64 encodes you will need
at least: (len / 3 + 1) * 4 + 4 bytes (+ 4 may be needed in case of
non-zero state). If you enable line-breaking you will need at least:
((len / 3 + 1) * 4 + 4) / 76 + 1 bytes of extra space.
break_lines is typically used when putting base64-encoded data in emails.
It breaks the lines at 76 columns instead of putting all of the text on
the same line. This avoids problems with long lines in the email system.
Note however that it breaks the lines with LF characters, not
CR LF sequences, so the result cannot be passed directly to SMTP
or certain other protocols.
Parameters:
in_— the binary data to encodebreak_lines— whether to break long linesstate— Saved state between steps, initialize to 0save— Saved state between steps, initialize to 0
basename¶
:::warning Deprecated since 2.2 This API is deprecated. :::
Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.
Parameters:
file_name— the name of the file
bit_lock¶
Sets the indicated lock_bit in address. If the bit is already
set, this call will block until bit_unlock unsets the
corresponding bit.
Attempting to lock on two different bits within the same integer is not supported and will very probably cause deadlocks.
The value of the bit that is set is (1u << bit). If bit is not
between 0 and 31 then the result is undefined.
This function accesses address atomically. All other accesses to
address must be atomic in order for this function to work
reliably. While address has a volatile qualifier, this is a historical
artifact and the argument passed to it should not be volatile.
Parameters:
address— a pointer to an integerlock_bit— a bit value between 0 and 31
bit_lock_and_get¶
Sets the indicated lock_bit in address and atomically returns the new value.
This is like bit_lock, except it can atomically return the new value at
address (right after obtaining the lock). Thus the value returned in out_val
always has the lock_bit set.
Parameters:
address— a pointer to an integerlock_bit— a bit value between 0 and 31
bit_nth_lsf¶
Find the position of the first bit set in mask, searching
from (but not including) nth_bit upwards. Bits are numbered
from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
usually). To start searching from the 0th bit, set nth_bit to -1.
Parameters:
mask— a #gulong containing flagsnth_bit— the index of the bit to start the search from
bit_nth_msf¶
Find the position of the first bit set in mask, searching
from (but not including) nth_bit downwards. Bits are numbered
from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
usually). To start searching from the last bit, set nth_bit to
-1 or GLIB_SIZEOF_LONG * 8.
Parameters:
mask— a #gulong containing flagsnth_bit— the index of the bit to start the search from
bit_storage¶
Gets the number of bits used to hold number,
e.g. if number is 4, 3 bits are needed.
Parameters:
number— a #guint
bit_trylock¶
Sets the indicated lock_bit in address, returning True if
successful. If the bit is already set, returns False immediately.
Attempting to lock on two different bits within the same integer is not supported.
The value of the bit that is set is (1u << bit). If bit is not
between 0 and 31 then the result is undefined.
This function accesses address atomically. All other accesses to
address must be atomic in order for this function to work
reliably. While address has a volatile qualifier, this is a historical
artifact and the argument passed to it should not be volatile.
Parameters:
address— a pointer to an integerlock_bit— a bit value between 0 and 31
bit_unlock¶
Clears the indicated lock_bit in address. If another thread is
currently blocked in bit_lock on this same bit then it will be
woken up.
This function accesses address atomically. All other accesses to
address must be atomic in order for this function to work
reliably. While address has a volatile qualifier, this is a historical
artifact and the argument passed to it should not be volatile.
Parameters:
address— a pointer to an integerlock_bit— a bit value between 0 and 31
bit_unlock_and_set¶
def bit_unlock_and_set(address: int | None, lock_bit: int, new_val: int, preserve_mask: int) -> None
This is like bit_unlock but also atomically sets address to
val.
If preserve_mask is not zero, then the preserve_mask bits will be
preserved in address and are not set to val.
Note that the lock_bit bit will always be unset regardless of
val, preserve_mask and the currently set value in address.
Parameters:
address— a pointer to an integerlock_bit— a bit value between 0 and 31new_val— the new value to setpreserve_mask— mask for bits fromaddressto preserve
blow_chunks¶
:::warning Deprecated since 2.10 This API is deprecated. :::
build_filenamev¶
Creates a filename from a vector of elements using the correct separator for the current platform.
This function behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.
If you are building a path programmatically you may want to use
PathBuf instead.
Parameters:
args—None-terminated array of strings containing the path elements.
build_pathv¶
def build_pathv(separator: str, args: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]]) -> str
Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of variadic arguments.
This function is mainly meant for language bindings.
Parameters:
separator— a string used to separate the elements of the path.args—None-terminated array of strings containing the path elements.
canonicalize_filename¶
def canonicalize_filename(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], relative_to: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = ...) -> str
Gets the canonical file name from filename. All triple slashes are turned into
single slashes, and all .. and .s resolved against relative_to.
Symlinks are not followed, and the returned path is guaranteed to be absolute.
If filename is an absolute path, relative_to is ignored. Otherwise,
relative_to will be prepended to filename to make it absolute. relative_to
must be an absolute path, or None. If relative_to is None, it'll fallback
to get_current_dir.
This function never fails, and will canonicalize file paths even if they don't exist.
No file system I/O is done.
Parameters:
filename— the name of the filerelative_to— the relative directory, orNoneto use the current working directory
chdir¶
A wrapper for the POSIX chdir() function. The function changes the
current directory of the process to path.
See your C library manual for more details about chdir().
Parameters:
path— a pathname in the GLib file name encoding (UTF-8 on Windows)
check_version¶
Checks that the GLib library in use is compatible with the given version.
Generally you would pass in the constants MAJOR_VERSION,
MINOR_VERSION, MICRO_VERSION as the three arguments
to this function; that produces a check that the library in use
is compatible with the version of GLib the application or module
was compiled against.
Compatibility is defined by two things: first the version
of the running library is newer than the version
@required_major.required_minor.@required_micro. Second
the running library must be binary compatible with the
version @required_major.@required_minor.@required_micro
(same major version.)
Parameters:
required_major— the required major versionrequired_minor— the required minor versionrequired_micro— the required micro version
child_watch_add¶
Sets a function to be called when the child indicated by pid
exits, at the priority priority.
If you obtain pid from spawn_async or
spawn_async_with_pipes you will need to pass
SpawnFlags.DO_NOT_REAP_CHILD as a flag to the spawn function for
the child watching to work.
In many programs, you will want to call spawn_check_wait_status
in the callback to determine whether or not the child exited
successfully.
Also, note that on platforms where GLib.Pid must be explicitly closed
(see spawn_close_pid) pid must not be closed while the source
is still active. Typically, you should invoke spawn_close_pid
in the callback function for the source.
GLib supports only a single callback per process ID.
On POSIX platforms, the same restrictions mentioned for
child_watch_source_new apply to this function.
This internally creates a main loop source using
child_watch_source_new and attaches it to the main loop context
using Source.attach. You can do these steps manually if you
need greater control.
Parameters:
priority— the priority of the idle source; typically this will be in the range betweenPRIORITY_DEFAULT_IDLEandPRIORITY_HIGH_IDLEpid— process to watch — on POSIX systems, this is the positive PID of a child process; on Windows it is a handle for a process (which doesn’t have to be a child)function— function to call
child_watch_source_new¶
Creates a new child watch source.
The source will not initially be associated with any
MainContext and must be added to one with
Source.attach before it will be executed.
Note that child watch sources can only be used in conjunction with
g_spawn... when the SpawnFlags.DO_NOT_REAP_CHILD flag is used.
Note that on platforms where GLib.Pid must be explicitly closed
(see spawn_close_pid) pid must not be closed while the
source is still active. Typically, you will want to call
spawn_close_pid in the callback function for the source.
On POSIX platforms, the following restrictions apply to this API due to limitations in POSIX process interfaces:
pidmust be a child of this process.pidmust be positive.- The application must not call
waitpid()with a non-positive first argument, for instance in another thread. - The application must not wait for
pidto exit by any other mechanism, includingwaitpid(pid, ...)or a second child-watch source for the samepid. - The application must not ignore
SIGCHLD. - Before 2.78, the application could not send a signal (
kill()) to the watchedpidin a race free manner. Since 2.78, you can do that while the associatedMainContextis acquired. - Before 2.78, even after destroying the
Source, you could not be sure thatpidwasn’t already reaped. Hence, it was also not safe tokill()orwaitpid()on the process ID after the child watch source was gone. Destroying the source before it fired made it impossible to reliably reap the process.
If any of those conditions are not met, this and related APIs will
not work correctly. This can often be diagnosed via a GLib warning
stating that ECHILD was received by waitpid().
Calling waitpid() for specific processes other than pid
remains a valid thing to do.
Parameters:
pid— process to watch — on POSIX systems, this is the positive PID of a child process; on Windows it is a handle for a process (which doesn’t have to be a child)
chmod¶
A wrapper for the POSIX chmod() function. The chmod() function is used to set the permissions of a file system object.
On Windows the file protection mechanism is not at all POSIX-like, and the underlying chmod() function in the C library just sets or clears the FAT-style READONLY attribute. It does not touch any ACL. Software that needs to manage file permissions on Windows exactly should use the Win32 API.
See your C library manual for more details about chmod().
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)mode— as in chmod()
clear_error¶
If err or *err is None, does nothing. Otherwise,
calls Error.free on *err and sets *err to None.
close¶
This wraps the close() call. In case of error, errno will be
preserved, but the error will also be stored as a Error in error.
In case of success, errno is undefined.
Besides using Error, there is another major reason to prefer this
function over the call provided by the system; on Unix, it will
attempt to correctly handle EINTR, which has platform-specific
semantics.
It is a bug to call this function with an invalid file descriptor.
On POSIX platforms since GLib 2.76, this function is async-signal safe
if (and only if) error is None and fd is a valid open file descriptor.
This makes it safe to call from a signal handler or a GSpawnChildSetupFunc
under those conditions.
See signal(7) and
signal-safety(7) for more details.
Parameters:
fd— A file descriptor
compute_checksum_for_bytes¶
Computes the checksum for a binary data. This is a
convenience wrapper for Checksum.new, Checksum.get_string
and Checksum.free.
The hexadecimal string returned will be in lower case.
Parameters:
checksum_type— aChecksumTypedata— binary blob to compute the digest of
compute_checksum_for_data¶
Computes the checksum for a binary data of length. This is a
convenience wrapper for Checksum.new, Checksum.get_string
and Checksum.free.
The hexadecimal string returned will be in lower case.
Parameters:
checksum_type— aChecksumTypedata— binary blob to compute the digest of
compute_checksum_for_string¶
def compute_checksum_for_string(checksum_type: ChecksumType | int, str: str, length: int) -> str | None
Computes the checksum of a string.
The hexadecimal string returned will be in lower case.
Parameters:
checksum_type— aChecksumTypestr— the string to compute the checksum oflength— the length of the string, or -1 if the string is null-terminated.
compute_hmac_for_bytes¶
Computes the HMAC for a binary data. This is a
convenience wrapper for Hmac.new, Hmac.get_string
and Hmac.unref.
The hexadecimal string returned will be in lower case.
Parameters:
digest_type— aChecksumTypeto use for the HMACkey— the key to use in the HMACdata— binary blob to compute the HMAC of
compute_hmac_for_data¶
Computes the HMAC for a binary data of length. This is a
convenience wrapper for Hmac.new, Hmac.get_string
and Hmac.unref.
The hexadecimal string returned will be in lower case.
Parameters:
digest_type— aChecksumTypeto use for the HMACkey— the key to use in the HMACdata— binary blob to compute the HMAC of
compute_hmac_for_string¶
def compute_hmac_for_string(digest_type: ChecksumType | int, key: list[int], str: str, length: int) -> str
Computes the HMAC for a string.
The hexadecimal string returned will be in lower case.
Parameters:
digest_type— aChecksumTypeto use for the HMACkey— the key to use in the HMACstr— the string to compute the HMAC forlength— the length of the string, or -1 if the string is nul-terminated
convert¶
Converts a string from one character set to another.
Note that you should use g_iconv() for streaming conversions.
Despite the fact that bytes_read can return information about partial
characters, the g_convert_... functions are not generally suitable
for streaming. If the underlying converter maintains internal state,
then this won't be preserved across successive calls to convert,
g_convert_with_iconv() or convert_with_fallback. (An example of
this is the GNU C converter for CP1255 which does not emit a base
character until it knows that the next character is not a mark that
could combine with the base character.)
Using extensions such as "//TRANSLIT" may not work (or may not work
well) on many platforms. Consider using str_to_ascii instead.
Parameters:
str— the string to convert.to_codeset— name of character set into which to convertstrfrom_codeset— character set ofstr.
convert_error_quark¶
convert_with_fallback¶
def convert_with_fallback(str: list[int], to_codeset: str, from_codeset: str, fallback: str) -> tuple[list[int], int]
Converts a string from one character set to another, possibly
including fallback sequences for characters not representable
in the output. Note that it is not guaranteed that the specification
for the fallback sequences in fallback will be honored. Some
systems may do an approximate conversion from from_codeset
to to_codeset in their iconv() functions,
in which case GLib will simply return that approximate conversion.
Note that you should use g_iconv() for streaming conversions.
Despite the fact that bytes_read can return information about partial
characters, the g_convert_... functions are not generally suitable
for streaming. If the underlying converter maintains internal state,
then this won't be preserved across successive calls to convert,
g_convert_with_iconv() or convert_with_fallback. (An example of
this is the GNU C converter for CP1255 which does not emit a base
character until it knows that the next character is not a mark that
could combine with the base character.)
Parameters:
str— the string to convert.to_codeset— name of character set into which to convertstrfrom_codeset— character set ofstr.fallback— UTF-8 string to use in place of characters not present in the target encoding. (The string must be representable in the target encoding). IfNone, characters not in the target encoding will be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
creat¶
A wrapper for the POSIX creat() function. The creat() function is used to convert a pathname into a file descriptor, creating a file if necessary.
On POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements creat() and file descriptors. The actual Windows API for opening files is different, see MSDN documentation for CreateFile(). The Win32 API uses file handles, which are more randomish integers, not small integers like file descriptors.
Because file descriptors are specific to the C library on Windows, the file descriptor returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the file descriptor returned by this function cannot be passed to C library functions like write() or read().
See your C library manual for more details about creat().
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)mode— as in creat()
datalist_foreach¶
Calls the given function for each data element of the datalist. The
function is called with each data element's GQuark id and data,
together with the given user_data parameter. Note that this
function is NOT thread-safe. So unless datalist can be protected
from any modifications during invocation of this function, it should
not be called.
func can make changes to datalist, but the iteration will not
reflect changes made during the datalist_foreach call, other
than skipping over elements that are removed.
Parameters:
datalist— a datalist.func— the function to call for each data element.
datalist_get_data¶
Gets a data element, using its string identifier. This is slower than
datalist_id_get_data because it compares strings.
Parameters:
datalist— a datalist.key— the string identifying a data element.
datalist_get_flags¶
Gets flags values packed in together with the datalist.
See datalist_set_flags.
Parameters:
datalist— pointer to the location that holds a list
datalist_id_get_data¶
Retrieves the data element corresponding to key_id.
Parameters:
datalist— a datalist.key_id— theGQuarkidentifying a data element.
datalist_id_remove_multiple¶
Removes multiple keys from a datalist.
This is more efficient than calling g_datalist_id_remove_data() multiple times in a row.
Before 2.80, n_keys had to be not larger than 16.
Since 2.84, performance is improved for larger number of keys.
Parameters:
datalist— a datalistkeys— keys to remove
datalist_set_flags¶
Turns on flag values for a data list. This function is used
to keep a small number of boolean flags in an object with
a data list without using any additional space. It is
not generally useful except in circumstances where space
is very tight. (It is used in the base GObject.Object type, for
example.)
Parameters:
datalist— pointer to the location that holds a listflags— the flags to turn on. The values of the flags are restricted byDATALIST_FLAGS_MASK(currently 3; giving two possible boolean flags). A value forflagsthat doesn't fit within the mask is an error.
datalist_unset_flags¶
Turns off flag values for a data list. See datalist_unset_flags
Parameters:
datalist— pointer to the location that holds a listflags— the flags to turn off. The values of the flags are restricted byDATALIST_FLAGS_MASK(currently 3: giving two possible boolean flags). A value forflagsthat doesn't fit within the mask is an error.
dataset_destroy¶
Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.
Parameters:
dataset_location— the location identifying the dataset.
dataset_foreach¶
Calls the given function for each data element which is associated
with the given location. Note that this function is NOT thread-safe.
So unless dataset_location can be protected from any modifications
during invocation of this function, it should not be called.
func can make changes to the dataset, but the iteration will not
reflect changes made during the dataset_foreach call, other
than skipping over elements that are removed.
Parameters:
dataset_location— the location identifying the dataset.func— the function to call for each data element.
dataset_id_get_data¶
Gets the data element corresponding to a GQuark.
Parameters:
dataset_location— the location identifying the dataset.key_id— theGQuarkid to identify the data element.
dcgettext¶
This is a variant of dgettext that allows specifying a locale
category instead of always using LC_MESSAGES. See dgettext for
more information about how this functions differs from calling
dcgettext() directly.
Parameters:
domain— the translation domain to use, orNoneto use the domain set with textdomain()msgid— message to translatecategory— a locale category
dgettext¶
This function is a wrapper of dgettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.
The advantage of using this function over dgettext() proper is that
libraries using this function (like GTK) will not use translations
if the application using the library does not have translations for
the current locale. This results in a consistent English-only
interface instead of one having partial translations. For this
feature to work, the call to textdomain() and setlocale() should
precede any dgettext invocations. For GTK, it means calling
textdomain() before Gtk.init or its variants.
This function disables translations if and only if upon its first call all the following conditions hold:
-
domainis notNone -
textdomain() has been called to set a default text domain
-
there is no translations available for the default text domain and the current locale
-
current locale is not "C" or any English locales (those starting with "en_")
Note that this behavior may not be desired for example if an application has its untranslated messages in a language other than English. In those cases the application should call textdomain() after initializing GTK.
Applications should normally not use this function directly, but use the _() macro for translations.
Parameters:
domain— the translation domain to use, orNoneto use the domain set with textdomain()msgid— message to translate
direct_equal¶
Compares two #gpointer arguments and returns True if they are equal.
It can be passed to g_hash_table_new() as the key_equal_func
parameter, when using opaque pointers compared by pointer value as
keys in a HashTable.
This equality function is also appropriate for keys that are integers
stored in pointers, such as GINT_TO_POINTER (n).
Parameters:
v1— a keyv2— a key to compare withv1
direct_hash¶
Converts a gpointer to a hash value.
It can be passed to g_hash_table_new() as the hash_func parameter,
when using opaque pointers compared by pointer value as keys in a
HashTable.
This hash function is also appropriate for keys that are integers
stored in pointers, such as GINT_TO_POINTER (n).
Parameters:
v— a #gpointer key
dngettext¶
This function is a wrapper of dngettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.
See dgettext for details of how this differs from dngettext()
proper.
Parameters:
domain— the translation domain to use, orNoneto use the domain set with textdomain()msgid— message to translatemsgid_plural— plural form of the messagen— the quantity for which translation is needed
double_equal¶
Compares the two #gdouble values being pointed to and returns
True if they are equal.
It can be passed to g_hash_table_new() as the key_equal_func
parameter, when using non-None pointers to doubles as keys in a
HashTable.
Parameters:
v1— a pointer to a #gdouble keyv2— a pointer to a #gdouble key to compare withv1
double_hash¶
Converts a pointer to a #gdouble to a hash value.
It can be passed to g_hash_table_new() as the hash_func parameter,
It can be passed to g_hash_table_new() as the hash_func parameter,
when using non-None pointers to doubles as keys in a HashTable.
Parameters:
v— a pointer to a #gdouble key
dpgettext¶
This function is a variant of dgettext which supports
a disambiguating message context. GNU gettext uses the
'\004' character to separate the message context and
message id in msgctxtid.
If 0 is passed as msgidoffset, this function will fall back to
trying to use the deprecated convention of using "|" as a separation
character.
This uses dgettext internally. See that functions for differences
with dgettext() proper.
Applications should normally not use this function directly, but use the C_() macro for translations with context.
Parameters:
domain— the translation domain to use, orNoneto use the domain set with textdomain()msgctxtid— a combined message context and message id, separated by a \004 charactermsgidoffset— the offset of the message id inmsgctxid
dpgettext2¶
This function is a variant of dgettext which supports
a disambiguating message context. GNU gettext uses the
'\004' character to separate the message context and
message id in msgctxtid.
This uses dgettext internally. See that functions for differences
with dgettext() proper.
This function differs from C_() in that it is not a macro and thus you may use non-string-literals as context and msgid arguments.
Parameters:
domain— the translation domain to use, orNoneto use the domain set with textdomain()context— the message contextmsgid— the message
environ_getenv¶
def environ_getenv(envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, variable: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str | None
Returns the value of the environment variable variable in the
provided list envp.
Parameters:
envp— an environment list (eg, as returned fromget_environ), orNonefor an empty environment listvariable— the environment variable to get
environ_setenv¶
def environ_setenv(envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, variable: str | bytes | os.PathLike[str] | os.PathLike[bytes], value: str | bytes | os.PathLike[str] | os.PathLike[bytes], overwrite: bool) -> list[str]
Sets the environment variable variable in the provided list
envp to value.
Parameters:
envp— an environment list that can be freed usingstrfreev(e.g., as returned fromget_environ), orNonefor an empty environment listvariable— the environment variable to set, must not contain '='value— the value for to set the variable tooverwrite— whether to change the variable if it already exists
environ_unsetenv¶
def environ_unsetenv(envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, variable: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> list[str]
Removes the environment variable variable from the provided
environment envp.
Parameters:
envp— an environment list that can be freed usingstrfreev(e.g., as returned fromget_environ), orNonefor an empty environment listvariable— the environment variable to remove, must not contain '='
file_error_from_errno¶
Gets a FileError constant based on the passed-in err_no.
For example, if you pass in EEXIST this function returns
FileError.EXIST. Unlike errno values, you can portably
assume that all FileError values will exist.
Normally a FileError value goes into a Error returned
from a function that manipulates files. So you would use
file_error_from_errno when constructing a Error.
Parameters:
err_no— an "errno" value
file_error_quark¶
file_get_contents¶
def file_get_contents(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> tuple[bool, list[int]]
Reads an entire file into allocated memory, with good error checking.
If the call was successful, it returns True and sets contents to the file
contents and length to the length of the file contents in bytes. The string
stored in contents will be nul-terminated, so for text files you can pass
None for the length argument. If the call was not successful, it returns
False and sets error. The error domain is G_FILE_ERROR. Possible error
codes are those in the FileError enumeration. In the error case,
contents is set to None and length is set to zero.
Parameters:
filename— name of a file to read contents from, in the GLib file name encoding
file_open_tmp¶
def file_open_tmp(tmpl: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = ...) -> tuple[int, str]
Opens a file for writing in the preferred directory for temporary
files (as returned by get_tmp_dir).
tmpl should be a string in the GLib file name encoding containing
a sequence of six 'X' characters, as the parameter to g_mkstemp().
However, unlike these functions, the template should only be a
basename, no directory components are allowed. If template is
None, a default template is used.
Note that in contrast to g_mkstemp() (and mkstemp()) tmpl is not
modified, and might thus be a read-only literal string.
Upon success, and if name_used is non-None, the actual name used
is returned in name_used. This string should be freed with free
when not needed any longer. The returned name is in the GLib file
name encoding.
Parameters:
tmpl— Template for file name, as in g_mkstemp(), basename only, orNonefor a default template
file_read_link¶
Reads the contents of the symbolic link filename like the POSIX
readlink() function.
The returned string is in the encoding used for filenames. Use
filename_to_utf8 to convert it to UTF-8.
The returned string may also be a relative path. Use g_build_filename() to convert it to an absolute path:
g_autoptr(GError) local_error = NULL;
g_autofree gchar *link_target = g_file_read_link ("/etc/localtime", &local_error);
if (local_error != NULL)
g_error ("Error reading link: %s", local_error->message);
if (!g_path_is_absolute (link_target))
{
g_autofree gchar *absolute_link_target = g_build_filename ("/etc", link_target, NULL);
g_free (link_target);
link_target = g_steal_pointer (&absolute_link_target);
}
Parameters:
filename— the symbolic link
file_set_contents¶
def file_set_contents(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], contents: list[int]) -> bool
Writes all of contents to a file named filename. This is a convenience
wrapper around calling file_set_contents_full with flags set to
G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING and
mode set to 0666.
Parameters:
filename— name of a file to writecontentsto, in the GLib file name encodingcontents— string to write to the file
file_set_contents_full¶
def file_set_contents_full(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], contents: list[int], flags: FileSetContentsFlags | int, mode: int) -> bool
Writes all of contents to a file named filename, with good error checking.
If a file called filename already exists it will be overwritten.
flags control the properties of the write operation: whether it’s atomic,
and what the tradeoff is between returning quickly or being resilient to
system crashes.
As this function performs file I/O, it is recommended to not call it anywhere
where blocking would cause problems, such as in the main loop of a graphical
application. In particular, if flags has any value other than
FileSetContentsFlags.NONE then this function may call fsync().
If FileSetContentsFlags.CONSISTENT is set in flags, the operation is atomic
in the sense that it is first written to a temporary file which is then
renamed to the final name.
Notes:
-
On UNIX, if
filenamealready exists hard links tofilenamewill break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. Iffilenameis a symbolic link, the link itself will be replaced, not the linked file. -
On UNIX, if
filenamealready exists and is non-empty, and if the system supports it (via a journalling filesystem or equivalent), and ifFileSetContentsFlags.CONSISTENTis set inflags, thefsync()call (or equivalent) will be used to ensure atomic replacement:filenamewill contain either its old contents orcontents, even in the face of system power loss, the disk being unsafely removed, etc. -
On UNIX, if
filenamedoes not already exist or is empty, there is a possibility that system power loss etc. after calling this function will leavefilenameempty or full of NUL bytes, depending on the underlying filesystem, unlessFileSetContentsFlags.DURABLEandFileSetContentsFlags.CONSISTENTare set inflags. -
On Windows renaming a file will not remove an existing file with the new name, so on Windows there is a race condition between the existing file being removed and the temporary file being renamed.
-
On Windows there is no way to remove a file that is open to some process, or mapped into memory. Thus, this function will fail if
filenamealready exists and is open.
If the call was successful, it returns True. If the call was not successful,
it returns False and sets error. The error domain is G_FILE_ERROR.
Possible error codes are those in the FileError enumeration.
Note that the name for the temporary file is constructed by appending up
to 7 characters to filename.
If the file didn’t exist before and is created, it will be given the
permissions from mode. Otherwise, the permissions of the existing file will
remain unchanged.
Parameters:
filename— name of a file to writecontentsto, in the GLib file name encodingcontents— string to write to the fileflags— flags controlling the safety vs speed of the operationmode— file mode, as passed toopen(); typically this will be0666
file_test¶
def file_test(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], test: FileTest | int) -> bool
Returns True if any of the tests in the bitfield test are
True. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)
will return True if the file exists; the check whether it's a
directory doesn't matter since the existence test is True. With
the current set of available tests, there's no point passing in
more than one test at a time.
Apart from FileTest.IS_SYMLINK all tests follow symbolic links,
so for a symbolic link to a regular file file_test will return
True for both FileTest.IS_SYMLINK and FileTest.IS_REGULAR.
Note, that for a dangling symbolic link file_test will return
True for FileTest.IS_SYMLINK and False for all other flags.
You should never use file_test to test whether it is safe
to perform an operation, because there is always the possibility
of the condition changing before you actually perform the operation,
see TOCTOU.
For example, you might think you could use FileTest.IS_SYMLINK
to know whether it is safe to write to a file without being
tricked into writing into a different location. It doesn't work!
// DON'T DO THIS
if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
{
fd = g_open (filename, O_WRONLY);
// write to fd
}
// DO THIS INSTEAD
fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
if (fd == -1)
{
// check error
if (errno == ELOOP)
// file is a symlink and can be ignored
else
// handle errors as before
}
else
{
// write to fd
}
Another thing to note is that FileTest.EXISTS and
FileTest.IS_EXECUTABLE are implemented using the access()
system call. This usually doesn't matter, but if your program
is setuid or setgid it means that these tests will give you
the answer for the real user ID and group ID, rather than the
effective user ID and group ID.
On Windows, there are no symlinks, so testing for
FileTest.IS_SYMLINK will always return False. Testing for
FileTest.IS_EXECUTABLE will just check that the file exists and
its name indicates that it is executable, checking for well-known
extensions and those listed in the PATHEXT environment variable.
Parameters:
filename— a filename to test in the GLib file name encodingtest— bitfield ofFileTestflags
filename_display_basename¶
Returns the display basename for the particular filename, guaranteed to be valid UTF-8. The display name might not be identical to the filename, for instance there might be problems converting it to UTF-8, and some files can be translated in the display.
If GLib cannot make sense of the encoding of filename, as a last resort it
replaces unknown characters with U+FFFD, the Unicode replacement character.
You can search the result for the UTF-8 encoding of this character (which is
"\357\277\275" in octal notation) to find out if filename was in an invalid
encoding.
You must pass the whole absolute pathname to this functions so that translation of well known locations can be done.
This function is preferred over filename_display_name if you know the
whole path, as it allows translation.
Parameters:
filename— an absolute pathname in the GLib file name encoding
filename_display_name¶
Converts a filename into a valid UTF-8 string. The conversion is
not necessarily reversible, so you should keep the original around
and use the return value of this function only for display purposes.
Unlike filename_to_utf8, the result is guaranteed to be non-None
even if the filename actually isn't in the GLib file name encoding.
If GLib cannot make sense of the encoding of filename, as a last resort it
replaces unknown characters with U+FFFD, the Unicode replacement character.
You can search the result for the UTF-8 encoding of this character (which is
"\357\277\275" in octal notation) to find out if filename was in an invalid
encoding.
If you know the whole pathname of the file you should use
filename_display_basename, since that allows location-based
translation of filenames.
Parameters:
filename— a pathname hopefully in the GLib file name encoding
filename_from_uri¶
Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.
Since GLib 2.78, the query string and fragment can be present in the URI, but are not part of the resulting filename. We take inspiration from https://url.spec.whatwg.org/#file-state, but we don't support the entire standard.
Parameters:
uri— a uri describing a filename (escaped, encoded in ASCII).
filename_from_utf8¶
Converts a string from UTF-8 to the encoding GLib uses for filenames. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.
The input string shall not contain nul characters even if the len
argument is positive. A nul character found inside the string will result
in error ConvertError.ILLEGAL_SEQUENCE. If the filename encoding is
not UTF-8 and the conversion output contains a nul character, the error
ConvertError.EMBEDDED_NUL is set and the function returns None.
Parameters:
utf8string— a UTF-8 encoded string.len— the length of the string, or -1 if the string is nul-terminated.
filename_to_uri¶
def filename_to_uri(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], hostname: str | None = ...) -> str
Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3. of RFC 2396.
Parameters:
filename— an absolute filename specified in the GLib file name encoding, which is the on-disk file name bytes on Unix, and UTF-8 on Windowshostname— A UTF-8 encoded hostname, orNonefor none.
filename_to_utf8¶
def filename_to_utf8(opsysstring: str | bytes | os.PathLike[str] | os.PathLike[bytes], len: int) -> tuple[str, int, int]
Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.
The input string shall not contain nul characters even if the len
argument is positive. A nul character found inside the string will result
in error ConvertError.ILLEGAL_SEQUENCE.
If the source encoding is not UTF-8 and the conversion output contains a
nul character, the error ConvertError.EMBEDDED_NUL is set and the
function returns None. Use convert to produce output that
may contain embedded nul characters.
Parameters:
opsysstring— a string in the encoding for filenameslen— the length of the string, or -1 if the string is nul-terminated (Note that some encodings may allow nul bytes to occur inside strings. In that case, using -1 for thelenparameter is unsafe)
find_program_in_path¶
def find_program_in_path(program: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str | None
Locates the first executable named program in the user's path, in the
same way that execvp() would locate it. Returns an allocated string
with the absolute path name, or None if the program is not found in
the path. If program is already an absolute path, returns a copy of
program if program exists and is executable, and None otherwise.
On Windows, if program does not have a file type suffix, tries
with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
the PATHEXT environment variable.
On Windows, it looks for the file in the same way as CreateProcess()
would. This means first in the directory where the executing
program was loaded from, then in the current directory, then in the
Windows 32-bit system directory, then in the Windows directory, and
finally in the directories in the PATH environment variable. If
the program is found, the return value contains the full name
including the type suffix.
Parameters:
program— a program name in the GLib file name encoding
fopen¶
A wrapper for the stdio fopen() function. The fopen() function
opens a file and associates a new stream with it.
Because file descriptors are specific to the C library on Windows,
and a file descriptor is part of the FILE struct, the FILE* returned
by this function makes sense only to functions in the same C library.
Thus if the GLib-using code uses a different C library than GLib does,
the FILE* returned by this function cannot be passed to C library
functions like fprintf() or fread().
See your C library manual for more details about fopen().
As close() and fclose() are part of the C library, this implies that it is
currently impossible to close a file if the application C library and the C library
used by GLib are different. Convenience functions like file_set_contents_full
avoid this problem.
Since GLib 2.86, the e option is supported in mode on all platforms. On
Unix platforms it will set O_CLOEXEC on the opened file descriptor. On
Windows platforms it will be converted to the
N modifier.
It is recommended to set e unconditionally, unless you know the returned
file should be shared between this process and a new fork.
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)mode— a string describing the mode in which the file should be opened
format_size¶
Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (kB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string "3.2 MB". The returned string is UTF-8, and may use a non-breaking space to separate the number and units, to ensure they aren’t separated when line wrapped.
The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
This string should be freed with free when not needed any longer.
See format_size_full for more options about how the size might be
formatted.
Parameters:
size— a size in bytes
format_size_for_display¶
:::warning Deprecated since 2.30 This API is deprecated. :::
Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string "3.1 MB".
The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
This string should be freed with free when not needed any longer.
Parameters:
size— a size in bytes
format_size_full¶
Formats a size.
This function is similar to format_size but allows for flags
that modify the output. See FormatSizeFlags.
Parameters:
size— a size in bytesflags—FormatSizeFlagsto modify the output
free¶
Frees the memory pointed to by mem.
If you know the allocated size of mem, calling free_sized may be faster,
depending on the libc implementation in use.
Starting from GLib 2.78, this may happen automatically in case a GCC
compatible compiler is used with some optimization level and the allocated
size is known at compile time (see documentation of
__builtin_object_size()
to understand its caveats).
If mem is None it simply returns, so there is no need to check mem
against None before calling this function.
Parameters:
mem— the memory to free
free_sized¶
Frees the memory pointed to by mem, assuming it is has the given size.
If mem is None this is a no-op (and size is ignored).
It is an error if size doesn’t match the size passed when mem was
allocated. size is passed to this function to allow optimizations in the
allocator. If you don’t know the allocation size, use free instead.
In case a GCC compatible compiler is used, this function may be used
automatically via free if the allocated size is known at compile time,
since GLib 2.78.
Parameters:
mem— the memory to freesize— size ofmem, in bytes
freopen¶
def freopen(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: str, stream: int | None = ...) -> int | None
A wrapper for the POSIX freopen() function. The freopen() function opens a file and associates it with an existing stream.
See your C library manual for more details about freopen().
Since GLib 2.86, the e option is supported in mode on all platforms. See
the documentation for fopen for more details.
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)mode— a string describing the mode in which the file should be openedstream— an existing stream which will be reused, orNone
fsync¶
A wrapper for the POSIX fsync() function. On Windows, _commit() will be
used. On macOS, fcntl(F_FULLFSYNC) will be used.
The fsync() function is used to synchronize a file's in-core
state with that of the disk.
This wrapper will handle retrying on EINTR.
See the C library manual for more details about fsync().
Parameters:
fd— a file descriptor
get_application_name¶
Gets a human-readable name for the application, as set by
set_application_name. This name should be localized if
possible, and is intended for display to the user. Contrast with
get_prgname, which gets a non-localized name. If
set_application_name has not been called, returns the result of
get_prgname (which may be None if set_prgname has also not
been called).
get_charset¶
Obtains the character set for the current locale;
you might use this character set as an argument to convert, to convert
from the current locale's encoding to some other encoding. (Frequently
locale_to_utf8 and locale_from_utf8 are nice shortcuts, though.)
On Windows the character set returned by this function is the so-called system default ANSI code-page. That is the character set used by the "narrow" versions of C library and Win32 functions that handle file names. It might be different from the character set used by the C library's current locale.
On Linux, the character set is found by consulting nl_langinfo() if
available. If not, the environment variables LC_ALL, LC_CTYPE, LANG
and CHARSET are queried in order. nl_langinfo() returns the C locale if
no locale has been loaded by setlocale().
The return value is True if the locale's encoding is UTF-8, in that
case you can perhaps avoid calling convert.
The string returned in charset is not allocated, and should not be
freed.
get_codeset¶
Gets the character set for the current locale.
get_console_charset¶
Obtains the character set used by the console attached to the process, which is suitable for printing output to the terminal.
Usually this matches the result returned by get_charset, but in
environments where the locale's character set does not match the encoding
of the console this function tries to guess a more suitable value instead.
On Windows the character set returned by this function is the output code page used by the console associated with the calling process. If the codepage can't be determined (for example because there is no console attached) UTF-8 is assumed.
The return value is True if the locale's encoding is UTF-8, in that
case you can perhaps avoid calling convert.
The string returned in charset is not allocated, and should not be
freed.
get_current_dir¶
Gets the current directory.
The returned string should be freed when no longer needed. The encoding of the returned string is system defined. On Windows, it is always UTF-8.
Since GLib 2.40, this function will return the value of the "PWD" environment variable if it is set and it happens to be the same as the current directory. This can make a difference in the case that the current directory is the target of a symbolic link.
get_current_time¶
:::warning Deprecated since 2.62 This API is deprecated. :::
Queries the system wall-clock time.
This is equivalent to the UNIX gettimeofday()
function, but portable.
You may find get_real_time to be more convenient.
Parameters:
result—TimeValstructure in which to store current time
get_environ¶
Gets the list of environment variables for the current process.
The list is None terminated and each item in the list is of the
form 'NAME=VALUE'.
This is equivalent to direct access to the 'environ' global variable, except portable.
The return value is freshly allocated and it should be freed with
strfreev when it is no longer needed.
get_filename_charsets¶
Determines the preferred character sets used for filenames.
The first character set from the charsets is the filename encoding, the
subsequent character sets are used when trying to generate a displayable
representation of a filename, see filename_display_name.
On Unix, the character sets are determined by consulting the
environment variables G_FILENAME_ENCODING and G_BROKEN_FILENAMES.
On Windows, the character set used in the GLib API is always UTF-8
and said environment variables have no effect.
G_FILENAME_ENCODING may be set to a comma-separated list of
character set names. The special token @locale is taken to mean the
character set for the current locale.
If G_FILENAME_ENCODING is not set, but G_BROKEN_FILENAMES is,
the character set of the current locale is taken as the filename
encoding. If neither environment variable is set, UTF-8 is taken
as the filename encoding, but the character set of the current locale
is also put in the list of encodings.
The returned charsets belong to GLib and must not be freed.
Note that on Unix, regardless of the locale character set or
G_FILENAME_ENCODING value, the actual file names present
on a system might be in any random encoding or just gibberish.
get_home_dir¶
Gets the current user's home directory.
As with most UNIX tools, this function will return the value of the
HOME environment variable if it is set to an existing absolute path
name, falling back to the passwd file in the case that it is unset.
If the path given in HOME is non-absolute, does not exist, or is
not a directory, the result is undefined.
Before version 2.36 this function would ignore the HOME environment
variable, taking the value from the passwd database instead. This was
changed to increase the compatibility of GLib with other programs (and
the XDG basedir specification) and to increase testability of programs
based on GLib (by making it easier to run them from test frameworks).
If your program has a strong requirement for either the new or the
old behaviour (and if you don't wish to increase your GLib
dependency to ensure that the new behaviour is in effect) then you
should either directly check the HOME environment variable yourself
or unset it before calling any functions in GLib.
get_host_name¶
Return a name for the machine.
The returned name is not necessarily a fully-qualified domain name, or even present in DNS or some other name service at all. It need not even be unique on your local network or site, but usually it is. Callers should not rely on the return value having any specific properties like uniqueness for security purposes. Even if the name of the machine is changed while an application is running, the return value from this function does not change. The returned string is owned by GLib and should not be modified or freed. If no name can be determined, a default fixed string "localhost" is returned.
The encoding of the returned string is UTF-8.
get_language_names¶
Computes a list of applicable locale names, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".
For example, if LANGUAGE=de:en_US, then the returned list is "de", "en_US", "en", "C".
This function consults the environment variables LANGUAGE, LC_ALL,
LC_MESSAGES and LANG to find the list of locales specified by the
user.
get_language_names_with_category¶
Computes a list of applicable locale names with a locale category name, which can be used to construct the fallback locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".
This function consults the environment variables LANGUAGE, LC_ALL,
category_name, and LANG to find the list of locales specified by the
user.
get_language_names returns get_language_names_with_category("LC_MESSAGES").
Parameters:
category_name— a locale category name
get_locale_variants¶
Returns a list of derived variants of locale, which can be used to
e.g. construct locale-dependent filenames or search paths. The returned
list is sorted from most desirable to least desirable.
This function handles territory, charset and extra locale modifiers. See
setlocale(3) for information about locales and their format.
locale itself is guaranteed to be returned in the output.
For example, if locale is fr_BE, then the returned list
is fr_BE, fr. If locale is en_GB.UTF-8@euro, then the returned list
is en_GB.UTF-8@euro, en_GB.UTF-8, en_GB@euro, en_GB, en.UTF-8@euro,
en.UTF-8, en@euro, en.
If you need the list of variants for the current locale,
use get_language_names.
Parameters:
locale— a locale identifier
get_monotonic_time¶
Queries the system monotonic time in microseconds.
The monotonic clock will always increase and doesn’t suffer discontinuities when the user (or NTP) changes the system time. It may or may not continue to tick during times where the machine is suspended.
We try to use the clock that corresponds as closely as possible to
the passage of time as measured by system calls such as
poll() but it
may not always be possible to do this.
A more accurate version of this function exists.
get_monotonic_time_ns returns the time in nanoseconds.
get_monotonic_time_ns¶
Queries the system monotonic time in nanoseconds.
The monotonic clock will always increase and doesn’t suffer discontinuities when the user (or NTP) changes the system time. It may or may not continue to tick during times where the machine is suspended.
We try to use the clock that corresponds as closely as possible to
the passage of time as measured by system calls such as
poll() but it
may not always be possible to do this.
Another version of this function exists.
get_monotonic_time returns the time in microseconds.
If you want to support older GLib versions, it is an alternative.
get_num_processors¶
Determine the approximate number of threads that the system will schedule simultaneously for this process. This is intended to be used as a parameter to g_thread_pool_new() for CPU bound tasks and similar cases.
get_os_info¶
Get information about the operating system.
On Linux this comes from the /etc/os-release file. On other systems, it may
come from a variety of sources. You can either use the standard key names
like G_OS_INFO_KEY_NAME or pass any UTF-8 string key name. For example,
/etc/os-release provides a number of other less commonly used values that may
be useful. No key is guaranteed to be provided, so the caller should always
check if the result is None.
Parameters:
key_name— a key for the OS info being requested, for exampleG_OS_INFO_KEY_NAME.
get_prgname¶
Gets the name of the program. This name should not be localized,
in contrast to get_application_name.
If you are using Gio.Application the program name is set in
Gio.Application.run. In case of GDK or GTK it is set in
gdk_init(), which is called by Gtk.init and the
Gtk.Application::startup handler. The program name is found by
taking the last component of argv[0].
get_real_name¶
Gets the real name of the user. This usually comes from the user's
entry in the passwd file. The encoding of the returned string is
system-defined. (On Windows, it is, however, always UTF-8.) If the
real user name cannot be determined, the string "Unknown" is
returned.
get_real_time¶
Queries the system wall-clock time.
This is equivalent to the UNIX gettimeofday()
function, but portable.
You should only use this call if you are actually interested in the real
wall-clock time. get_monotonic_time is probably more useful for
measuring intervals.
get_system_config_dirs¶
Returns an ordered list of base directories in which to access system-wide configuration information.
On UNIX platforms this is determined using the mechanisms described
in the
XDG Base Directory Specification.
In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
On Windows it follows XDG Base Directory Specification if XDG_CONFIG_DIRS is defined.
If XDG_CONFIG_DIRS is undefined, the directory that contains application
data for all users is used instead. A typical path is
C:\Documents and Settings\All Users\Application Data.
This folder is used for application data
that is not user specific. For example, an application can store
a spell-check dictionary, a database of clip art, or a log file in the
FOLDERID_ProgramData folder. This information will not roam and is available
to anyone using the computer.
The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.
get_system_data_dirs¶
Returns an ordered list of base directories in which to access system-wide application data.
On UNIX platforms this is determined using the mechanisms described
in the
XDG Base Directory Specification
In this case the list of directories retrieved will be XDG_DATA_DIRS.
On Windows it follows XDG Base Directory Specification if XDG_DATA_DIRS is defined.
If XDG_DATA_DIRS is undefined,
the first elements in the list are the Application Data
and Documents folders for All Users. (These can be determined only
on Windows 2000 or later and are not present in the list on other
Windows versions.) See documentation for FOLDERID_ProgramData and
FOLDERID_PublicDocuments.
Then follows the "share" subfolder in the installation folder for the package containing the DLL that calls this function, if it can be determined.
Finally the list contains the "share" subfolder in the installation folder for GLib, and in the installation folder for the package the application's .exe file belongs to.
The installation folders above are determined by looking up the folder where the module (DLL or EXE) in question is located. If the folder's name is "bin", its parent is used, otherwise the folder itself.
Note that on Windows the returned list can vary depending on where this function is called.
The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.
get_tmp_dir¶
Gets the directory to use for temporary files.
On UNIX, this is taken from the TMPDIR environment variable.
If the variable is not set, P_tmpdir is
used, as defined by the system C library. Failing that, a
hard-coded default of "/tmp" is returned.
On Windows, the TEMP environment variable is used, with the
root directory of the Windows installation (eg: "C:\") used
as a default.
The encoding of the returned string is system-defined. On Windows,
it is always UTF-8. The return value is never None or the empty
string.
get_user_cache_dir¶
Returns a base directory in which to store non-essential, cached data specific to particular user.
On UNIX platforms this is determined using the mechanisms described
in the
XDG Base Directory Specification.
In this case the directory retrieved will be XDG_CACHE_HOME.
On Windows it follows XDG Base Directory Specification if XDG_CACHE_HOME is defined.
If XDG_CACHE_HOME is undefined, the directory that serves as a common
repository for temporary Internet files is used instead. A typical path is
C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
See the documentation for FOLDERID_InternetCache.
The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.
get_user_config_dir¶
Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.
On UNIX platforms this is determined using the mechanisms described
in the
XDG Base Directory Specification.
In this case the directory retrieved will be XDG_CONFIG_HOME.
On Windows it follows XDG Base Directory Specification if XDG_CONFIG_HOME is defined.
If XDG_CONFIG_HOME is undefined, the folder to use for local (as opposed
to roaming) application data is used instead. See the
documentation for FOLDERID_LocalAppData.
Note that in this case on Windows it will be the same
as what get_user_data_dir returns.
The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.
get_user_data_dir¶
Returns a base directory in which to access application data such as icons that is customized for a particular user.
On UNIX platforms this is determined using the mechanisms described
in the
XDG Base Directory Specification.
In this case the directory retrieved will be XDG_DATA_HOME.
On Windows it follows XDG Base Directory Specification if XDG_DATA_HOME
is defined. If XDG_DATA_HOME is undefined, the folder to use for local (as
opposed to roaming) application data is used instead. See the
documentation for FOLDERID_LocalAppData.
Note that in this case on Windows it will be the same
as what get_user_config_dir returns.
The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.
get_user_name¶
Gets the user name of the current user. The encoding of the returned string is system-defined. On UNIX, it might be the preferred file name encoding, or something else, and there is no guarantee that it is even consistent on a machine. On Windows, it is always UTF-8.
get_user_runtime_dir¶
Returns a directory that is unique to the current user on the local system.
This is determined using the mechanisms described
in the
XDG Base Directory Specification.
This is the directory
specified in the XDG_RUNTIME_DIR environment variable.
In the case that this variable is not set, we return the value of
get_user_cache_dir, after verifying that it exists.
The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.
get_user_special_dir¶
Returns the full path of a special directory using its logical id.
On UNIX this is done using the XDG special user directories.
For compatibility with existing practise, UserDirectory.DIRECTORY_DESKTOP
falls back to $HOME/Desktop when XDG special user directories have
not been set up.
Depending on the platform, the user might be able to change the path of the special directory without requiring the session to restart; GLib will not reflect any change once the special directories are loaded.
Parameters:
directory— the logical id of special directory
get_user_state_dir¶
Returns a base directory in which to store state files specific to particular user.
On UNIX platforms this is determined using the mechanisms described
in the
XDG Base Directory Specification.
In this case the directory retrieved will be XDG_STATE_HOME.
On Windows it follows XDG Base Directory Specification if XDG_STATE_HOME is defined.
If XDG_STATE_HOME is undefined, the folder to use for local (as opposed
to roaming) application data is used instead. See the
documentation for FOLDERID_LocalAppData.
Note that in this case on Windows it will be the same
as what get_user_data_dir returns.
The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.
getenv¶
Returns the value of an environment variable.
On UNIX, the name and value are byte strings which might or might not be in some consistent character set and encoding. On Windows, they are in UTF-8. On Windows, in case the environment variable's value contains references to other environment variables, they are expanded.
Parameters:
variable— the environment variable to get
hostname_is_ascii_encoded¶
Tests if hostname contains segments with an ASCII-compatible
encoding of an Internationalized Domain Name. If this returns
True, you should decode the hostname with hostname_to_unicode
before displaying it to the user.
Note that a hostname might contain a mix of encoded and unencoded
segments, and so it is possible for hostname_is_non_ascii and
hostname_is_ascii_encoded to both return True for a name.
Parameters:
hostname— a hostname
hostname_is_ip_address¶
Tests if hostname is the string form of an IPv4 or IPv6 address.
(Eg, "192.168.0.1".)
Since 2.66, IPv6 addresses with a zone-id are accepted (RFC6874).
Parameters:
hostname— a hostname (or IP address in string form)
hostname_is_non_ascii¶
Tests if hostname contains Unicode characters. If this returns
True, you need to encode the hostname with hostname_to_ascii
before using it in non-IDN-aware contexts.
Note that a hostname might contain a mix of encoded and unencoded
segments, and so it is possible for hostname_is_non_ascii and
hostname_is_ascii_encoded to both return True for a name.
Parameters:
hostname— a hostname
hostname_to_ascii¶
Converts hostname to its canonical ASCII form; an ASCII-only
string containing no uppercase letters and not ending with a
trailing dot.
Parameters:
hostname— a valid UTF-8 or ASCII hostname
hostname_to_unicode¶
Converts hostname to its canonical presentation form; a UTF-8
string in Unicode normalization form C, containing no uppercase
letters, no forbidden characters, and no ASCII-encoded segments,
and not ending with a trailing dot.
Of course if hostname is not an internationalized hostname, then
the canonical presentation form will be entirely ASCII.
Parameters:
hostname— a valid UTF-8 or ASCII hostname
idle_add¶
Adds a function to be called whenever there are no higher priority events pending.
If the function returns SOURCE_REMOVE it is automatically
removed from the list of event sources and will not be called again.
See main loop memory management for details
on how to handle the return value and memory management of data.
This internally creates a main loop source using idle_source_new
and attaches it to the global MainContext using
Source.attach, so the callback will be invoked in whichever
thread is running that main context. You can do these steps manually if you
need greater control or to use a custom main context.
Parameters:
priority— the priority of the idle source; typically this will be in the range betweenPRIORITY_DEFAULT_IDLEandPRIORITY_HIGH_IDLEfunction— function to call
idle_remove_by_data¶
Removes the idle function with the given data.
Parameters:
data— the data for the idle source’s callback.
idle_source_new¶
Creates a new idle source.
The source will not initially be associated with any
MainContext and must be added to one with
Source.attach before it will be executed. Note that the
default priority for idle sources is PRIORITY_DEFAULT_IDLE, as
compared to other sources which have a default priority of
PRIORITY_DEFAULT.
int64_equal¶
Compares the two #gint64 values being pointed to and returns
True if they are equal.
It can be passed to g_hash_table_new() as the key_equal_func
parameter, when using non-None pointers to 64-bit integers as keys in a
HashTable.
Parameters:
v1— a pointer to a #gint64 keyv2— a pointer to a #gint64 key to compare withv1
int64_hash¶
Converts a pointer to a #gint64 to a hash value.
It can be passed to g_hash_table_new() as the hash_func parameter,
when using non-None pointers to 64-bit integer values as keys in a
HashTable.
Parameters:
v— a pointer to a #gint64 key
int_equal¶
Compares the two #gint values being pointed to and returns
True if they are equal.
It can be passed to g_hash_table_new() as the key_equal_func
parameter, when using non-None pointers to integers as keys in a
HashTable.
Note that this function acts on pointers to #gint, not on #gint
directly: if your hash table's keys are of the form
GINT_TO_POINTER (n), use direct_equal instead.
Parameters:
v1— a pointer to a #gint keyv2— a pointer to a #gint key to compare withv1
int_hash¶
Converts a pointer to a #gint to a hash value.
It can be passed to g_hash_table_new() as the hash_func parameter,
when using non-None pointers to integer values as keys in a HashTable.
Note that this function acts on pointers to #gint, not on #gint
directly: if your hash table's keys are of the form
GINT_TO_POINTER (n), use direct_hash instead.
Parameters:
v— a pointer to a #gint key
intern_static_string¶
Returns a canonical representation for string. Interned strings
can be compared for equality by comparing the pointers, instead of
using strcmp(). intern_static_string does not copy the string,
therefore string must not be freed or modified.
This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.
Parameters:
string— a static string
intern_string¶
Returns a canonical representation for string. Interned strings
can be compared for equality by comparing the pointers, instead of
using strcmp().
This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.
Parameters:
string— a string
io_add_watch¶
def io_add_watch(channel: IOChannel, priority: int, condition: IOCondition | int, func: IOFunc) -> int
Adds the IOChannel into the default main loop context
with the given priority.
This internally creates a main loop source using io_create_watch
and attaches it to the main loop context with Source.attach.
You can do these steps manually if you need greater control.
Parameters:
channel— aIOChannelpriority— the priority of theIOChannelsourcecondition— the condition to watch forfunc— the function to call when the condition is satisfied
io_create_watch¶
Creates a Source that's dispatched when condition is met for the
given channel. For example, if condition is GObject.IOCondition.IN, the source will
be dispatched when there's data available for reading.
The callback function invoked by the Source should be added with
Source.set_callback, but it has type GIOFunc (not GSourceFunc).
g_io_add_watch() is a simpler interface to this same functionality, for the case where you want to add the source to the default main loop context at the default priority.
On Windows, polling a Source created to watch a channel for a socket
puts the socket in non-blocking mode. This is a side-effect of the
implementation and unavoidable.
Parameters:
channel— aIOChannelto watchcondition— conditions to watch for
listenv¶
Gets the names of all variables set in the environment.
Programs that want to be portable to Windows should typically use
this function and getenv instead of using the environ array
from the C library directly. On Windows, the strings in the environ
array are in system codepage encoding, while in most of the typical
use cases for environment variables in GLib-using programs you want
the UTF-8 encoding that this function and getenv provide.
locale_from_utf8¶
Converts a string from UTF-8 to the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale. On Windows this means the system codepage.
The input string shall not contain nul characters even if the len
argument is positive. A nul character found inside the string will result
in error ConvertError.ILLEGAL_SEQUENCE. Use convert to convert
input that may contain embedded nul characters.
Parameters:
utf8string— a UTF-8 encoded stringlen— the length of the string, or -1 if the string is nul-terminated.
locale_to_utf8¶
Converts a string which is in the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale into a UTF-8 string.
If the source encoding is not UTF-8 and the conversion output contains a
nul character, the error ConvertError.EMBEDDED_NUL is set and the
function returns None.
If the source encoding is UTF-8, an embedded nul character is treated with
the ConvertError.ILLEGAL_SEQUENCE error for backward compatibility with
earlier versions of this library. Use convert to produce output that
may contain embedded nul characters.
Parameters:
opsysstring— a string in the encoding of the current locale. On Windows this means the system codepage.
log_default_handler¶
def log_default_handler(log_domain: str | None, log_level: LogLevelFlags | int, message: str | None = ..., unused_data: int | None = ...) -> None
The default log handler set up by GLib; GLib.log_set_default_handler
allows to install an alternate default log handler.
This is used if no log handler has been set for the particular log
domain and log level combination. It outputs the message to stderr
or stdout and if the log level is fatal it calls GLib.BREAKPOINT. It automatically
prints a new-line character after the message, so one does not need to be
manually included in message.
The behavior of this log handler can be influenced by a number of environment variables:
G_MESSAGES_PREFIXED: A:-separated list of log levels for which messages should be prefixed by the program name and PID of the application.G_MESSAGES_DEBUG: A space-separated list of log domains for which debug and informational messages are printed. By default these messages are not printed. If you need to set the allowed domains at runtime, uselog_writer_default_set_debug_domains.DEBUG_INVOCATION: If set to1, this is equivalent toG_MESSAGES_DEBUG=all.DEBUG_INVOCATIONis a standard environment variable set by systemd to prompt debug output. (Since: 2.84)
stderr is used for levels LogLevelFlags.LEVEL_ERROR,
LogLevelFlags.LEVEL_CRITICAL, LogLevelFlags.LEVEL_WARNING and
LogLevelFlags.LEVEL_MESSAGE. stdout is used for
the rest, unless stderr was requested by
log_writer_default_set_use_stderr.
This has no effect if structured logging is enabled; see Using Structured Logging.
Parameters:
log_domain— the log domain of the message, orNULLfor the default""application domainlog_level— the level of the messagemessage— the messageunused_data— data passed fromGLib.logwhich is unused
log_get_always_fatal¶
Gets the current fatal mask.
This is mostly used by custom log writers to make fatal messages
(fatal-warnings, fatal-criticals) work as expected, when using the
G_DEBUG environment variable (see Running GLib Applications).
An example usage is shown below:
static GLogWriterOutput
my_custom_log_writer_fn (GLogLevelFlags log_level,
const GLogField *fields,
gsize n_fields,
gpointer user_data)
{
// abort if the message was fatal
if (log_level & g_log_get_always_fatal ())
g_abort ();
// custom log handling code
...
...
// success
return G_LOG_WRITER_HANDLED;
}
log_get_debug_enabled¶
Return whether debug output from the GLib logging system is enabled.
Note that this should not be used to conditionalise calls to GLib.debug or
other logging functions; it should only be used from LogWriterFunc
implementations.
Note also that the value of this does not depend on G_MESSAGES_DEBUG, nor
DEBUG_INVOCATION, nor log_writer_default_set_debug_domains; see
the docs for log_set_debug_enabled.
log_remove_handler¶
Removes the log handler.
This has no effect if structured logging is enabled; see Using Structured Logging.
Parameters:
log_domain— the log domainhandler_id— the ID of the handler, which was returned inlog_set_handler
log_set_always_fatal¶
Sets the message levels which are always fatal, in any log domain.
When a message with any of these levels is logged the program terminates.
You can only set the levels defined by GLib to be fatal.
LogLevelFlags.LEVEL_ERROR is always fatal.
You can also make some message levels fatal at runtime by setting
the G_DEBUG environment variable (see
Running GLib Applications).
Libraries should not call this function, as it affects all messages logged by a process, including those from other libraries.
Structured log messages (using GLib.log_structured and
log_structured_array) are fatal only if the default log writer is used;
otherwise it is up to the writer function to determine which log messages
are fatal. See Using Structured Logging.
Parameters:
fatal_mask— the mask containing bits set for each level of error which is to be fatal
log_set_debug_enabled¶
Enable or disable debug output from the GLib logging system for all domains.
This value interacts disjunctively with G_MESSAGES_DEBUG, DEBUG_INVOCATION and
log_writer_default_set_debug_domains — if any of them would allow
a debug message to be outputted, it will be.
Note that this should not be used from within library code to enable debug output — it is intended for external use.
Parameters:
enabled—TRUEto enable debug output,FALSEotherwise
log_set_fatal_mask¶
Sets the log levels which are fatal in the given domain.
LogLevelFlags.LEVEL_ERROR is always fatal.
This has no effect on structured log messages (using GLib.log_structured or
log_structured_array). To change the fatal behaviour for specific log
messages, programs must install a custom log writer function using
log_set_writer_func. See
Using Structured Logging.
This function is mostly intended to be used with
LogLevelFlags.LEVEL_CRITICAL. You should typically not set
LogLevelFlags.LEVEL_WARNING, LogLevelFlags.LEVEL_MESSAGE, LogLevelFlags.LEVEL_INFO or
LogLevelFlags.LEVEL_DEBUG as fatal except inside of test programs.
Parameters:
log_domain— the log domainfatal_mask— the new fatal mask
log_set_handler¶
def log_set_handler(log_domain: str | None, log_levels: LogLevelFlags | int, log_func: LogFunc) -> int
Like log_set_handler, but takes a destroy notify for the user_data.
This has no effect if structured logging is enabled; see Using Structured Logging.
The log_domain parameter can be set to NULL or an empty string to use the default
application domain.
Parameters:
log_domain— the log domain application domainlog_levels— the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with theLogLevelFlags.FLAG_FATALandLogLevelFlags.FLAG_RECURSIONbit flags.log_func— the log handler function
log_set_writer_func¶
Set a writer function which will be called to format and write out each log message.
Each program should set a writer function, or the default writer
(log_writer_default) will be used.
Libraries must not call this function — only programs are allowed to install a writer function, as there must be a single, central point where log messages are formatted and outputted.
There can only be one writer function. It is an error to set more than one.
log_structured_array¶
Log a message with structured data.
The message will be passed through to the log writer set by the application
using log_set_writer_func. If the
message is fatal (i.e. its log level is LogLevelFlags.LEVEL_ERROR), the program will
be aborted at the end of this function.
See GLib.log_structured for more documentation.
This assumes that log_level is already present in fields (typically as the
PRIORITY field).
Parameters:
log_level— log level, either fromLogLevelFlags, or a user-defined levelfields— key–value pairs of structured data to add to the log message
log_variant¶
Log a message with structured data, accepting the data within a Variant.
This version is especially useful for use in other languages, via introspection.
The only mandatory item in the fields dictionary is the "MESSAGE" which must
contain the text shown to the user.
The values in the fields dictionary are likely to be of type G_VARIANT_TYPE_STRING.
Array of bytes (G_VARIANT_TYPE_BYTESTRING) is also
supported. In this case the message is handled as binary and will be forwarded
to the log writer as such. The size of the array should not be higher than
G_MAXSSIZE. Otherwise it will be truncated to this size. For other types
Variant.print will be used to convert the value into a string.
For more details on its usage and about the parameters, see GLib.log_structured.
Parameters:
log_domain— log domain, usuallyG_LOG_DOMAINlog_level— log level, either fromLogLevelFlags, or a user-defined levelfields— a dictionary (Variantof the typeG_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.
log_writer_default¶
def log_writer_default(log_level: LogLevelFlags | int, fields: list[LogField], user_data: int | None = ...) -> LogWriterOutput
Format a structured log message and output it to the default log destination for the platform.
On Linux, this is typically the systemd journal, falling
back to stdout or stderr if running from the terminal or if output is
being redirected to a file.
Support for other platform-specific logging mechanisms may be added in future. Distributors of GLib may modify this function to impose their own (documented) platform-specific log writing policies.
This is suitable for use as a LogWriterFunc, and is the default writer used
if no other is set using log_set_writer_func.
As with log_default_handler, this function drops debug and informational
messages unless their log domain (or all) is listed in the space-separated
G_MESSAGES_DEBUG environment variable, or DEBUG_INVOCATION=1 is set in
the environment, or set at runtime by log_writer_default_set_debug_domains.
log_writer_default uses the mask set by log_set_always_fatal to
determine which messages are fatal. When using a custom writer function instead it is
up to the writer function to determine which log messages are fatal.
Parameters:
log_level— log level, either fromLogLevelFlags, or a user-defined levelfields— key–value pairs of structured data forming the log messageuser_data— user data passed tolog_set_writer_func
log_writer_default_set_debug_domains¶
Reset the list of domains to be logged, that might be initially set by the
G_MESSAGES_DEBUG or DEBUG_INVOCATION environment variables.
This function is thread-safe.
Parameters:
domains—NULL-terminated array with domains to be printed.NULLor an array with no values means none. Array with a single value"all"means all.
log_writer_default_set_use_stderr¶
Configure whether the built-in log functions will output all log messages to
stderr.
The built-in log functions are log_default_handler for the
old-style API, and both log_writer_default and
log_writer_standard_streams for the structured API.
By default, log messages of levels LogLevelFlags.LEVEL_INFO and
LogLevelFlags.LEVEL_DEBUG are sent to stdout, and other log messages are
sent to stderr. This is problematic for applications that intend
to reserve stdout for structured output such as JSON or XML.
This function sets global state. It is not thread-aware, and should be called at the very start of a program, before creating any other threads or creating objects that could create worker threads of their own.
Parameters:
use_stderr— IfTRUE, usestderrfor log messages that would normally have appeared onstdout
log_writer_default_would_drop¶
def log_writer_default_would_drop(log_level: LogLevelFlags | int, log_domain: str | None = ...) -> bool
Check whether log_writer_default and log_default_handler would
ignore a message with the given domain and level.
As with log_default_handler, this function drops debug and informational
messages unless their log domain (or all) is listed in the space-separated
G_MESSAGES_DEBUG environment variable, or DEBUG_INVOCATION=1 is set in
the environment, or by log_writer_default_set_debug_domains.
This can be used when implementing log writers with the same filtering behaviour as the default, but a different destination or output format:
if (g_log_writer_default_would_drop (log_level, log_domain))
return G_LOG_WRITER_HANDLED;
]|
or to skip an expensive computation if it is only needed for a debugging
message, and `G_MESSAGES_DEBUG` and `DEBUG_INVOCATION` are not set:
```c
if ( (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN))
{
g_autofree gchar *result = expensive_computation (my_object);
g_debug ("my_object result: `s`", result);
}
Parameters:
log_level— log level, either fromLogLevelFlags, or a user-defined levellog_domain— log domain
log_writer_format_fields¶
def log_writer_format_fields(log_level: LogLevelFlags | int, fields: list[LogField], use_color: bool) -> str
Format a structured log message as a string suitable for outputting to the terminal (or elsewhere).
This will include the values of all fields it knows
how to interpret, which includes MESSAGE and GLIB_DOMAIN (see the
documentation for GLib.log_structured). It does not include values from
unknown fields.
The returned string does not have a trailing new-line character. It is encoded in the character set of the current locale, which is not necessarily UTF-8.
Parameters:
log_level— log level, either fromLogLevelFlags, or a user-defined levelfields— key–value pairs of structured data forming the log messageuse_color—TRUEto use ANSI color escape sequences when formatting the message,FALSEto not
log_writer_is_journald¶
Check whether the given output_fd file descriptor is a connection to the
systemd journal, or something else (like a log file or stdout or
stderr).
Invalid file descriptors are accepted and return FALSE, which allows for
the following construct without needing any additional error handling:
Parameters:
output_fd— output file descriptor to check
log_writer_journald¶
def log_writer_journald(log_level: LogLevelFlags | int, fields: list[LogField], user_data: int | None = ...) -> LogWriterOutput
Format a structured log message and send it to the systemd journal as a set of key–value pairs.
All fields are sent to the journal, but if a field has length zero (indicating program-specific data) then only its key will be sent.
This is suitable for use as a LogWriterFunc.
If GLib has been compiled without systemd support, this function is still
defined, but will always return LogWriterOutput.UNHANDLED.
Parameters:
log_level— log level, either fromLogLevelFlags, or a user-defined levelfields— key–value pairs of structured data forming the log messageuser_data— user data passed tolog_set_writer_func
log_writer_standard_streams¶
def log_writer_standard_streams(log_level: LogLevelFlags | int, fields: list[LogField], user_data: int | None = ...) -> LogWriterOutput
Format a structured log message and print it to either stdout or stderr,
depending on its log level.
LogLevelFlags.LEVEL_INFO and LogLevelFlags.LEVEL_DEBUG messages
are sent to stdout, or to stderr if requested by
log_writer_default_set_use_stderr;
all other log levels are sent to stderr. Only fields
which are understood by this function are included in the formatted string
which is printed.
If the output stream supports ANSI color escape sequences, they will be used in the output.
A trailing new-line character is added to the log message when it is printed.
This is suitable for use as a LogWriterFunc.
Parameters:
log_level— log level, either fromLogLevelFlags, or a user-defined levelfields— key–value pairs of structured data forming the log messageuser_data— user data passed tolog_set_writer_func
log_writer_supports_color¶
Check whether the given output_fd file descriptor supports
ANSI color escape sequences.
If so, they can safely be used when formatting log messages.
Parameters:
output_fd— output file descriptor to check
log_writer_syslog¶
def log_writer_syslog(log_level: LogLevelFlags | int, fields: list[LogField], user_data: int | None = ...) -> LogWriterOutput
Format a structured log message and send it to the syslog daemon. Only fields which are understood by this function are included in the formatted string which is printed.
Log facility will be defined via the SYSLOG_FACILITY field and accepts the following values: "auth", "daemon", and "user". If SYSLOG_FACILITY is not specified, LOG_USER facility will be used.
This is suitable for use as a LogWriterFunc.
If syslog is not supported, this function is still defined, but will always
return LogWriterOutput.UNHANDLED.
Parameters:
log_level— log level, either fromLogLevelFlags, or a user-defined levelfields— key–value pairs of structured data forming the log messageuser_data— user data passed tolog_set_writer_func
lstat¶
A wrapper for the POSIX lstat() function. The lstat() function is
like stat() except that in the case of symbolic links, it returns
information about the symbolic link itself and not the file that it
refers to. If the system does not support symbolic links lstat
is identical to stat.
See your C library manual for more details about lstat().
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)buf— a pointer to a stat struct, which will be filled with the file information
main_current_source¶
Returns the currently firing source for this thread.
main_depth¶
Returns the depth of the stack of calls to
MainContext.dispatch on any MainContext in the current thread.
That is, when called from the top level, it gives 0. When
called from within a callback from MainContext.iteration
(or MainLoop.run, etc.) it returns 1. When called from within
a callback to a recursive call to MainContext.iteration,
it returns 2. And so forth.
This function is useful in a situation like the following: Imagine an extremely simple ‘garbage collected’ system.
static GList *free_list;
gpointer
allocate_memory (gsize size)
{
gpointer result = g_malloc (size);
free_list = g_list_prepend (free_list, result);
return result;
}
void
free_allocated_memory (void)
{
GList *l;
for (l = free_list; l; l = l->next);
g_free (l->data);
g_list_free (free_list);
free_list = NULL;
}
[...]
while (TRUE);
{
g_main_context_iteration (NULL, TRUE);
free_allocated_memory();
}
This works from an application, however, if you want to do the same
thing from a library, it gets more difficult, since you no longer
control the main loop. You might think you can simply use an idle
function to make the call to free_allocated_memory(), but that
doesn’t work, since the idle function could be called from a
recursive callback. This can be fixed by using main_depth
gpointer
allocate_memory (gsize size)
{
FreeListBlock *block = g_new (FreeListBlock, 1);
block->mem = g_malloc (size);
block->depth = g_main_depth ();
free_list = g_list_prepend (free_list, block);
return block->mem;
}
void
free_allocated_memory (void)
{
GList *l;
int depth = g_main_depth ();
for (l = free_list; l; );
{
GList *next = l->next;
FreeListBlock *block = l->data;
if (block->depth > depth)
{
g_free (block->mem);
g_free (block);
free_list = g_list_delete_link (free_list, l);
}
l = next;
}
}
There is a temptation to use main_depth to solve
problems with reentrancy. For instance, while waiting for data
to be received from the network in response to a menu item,
the menu item might be selected again. It might seem that
one could make the menu item’s callback return immediately
and do nothing if main_depth returns a value greater than 1.
However, this should be avoided since the user then sees selecting
the menu item do nothing. Furthermore, you’ll find yourself adding
these checks all over your code, since there are doubtless many,
many things that the user could do. Instead, you can use the
following techniques:
-
Use
gtk_widget_set_sensitive()or modal dialogs to prevent the user from interacting with elements while the main loop is recursing. -
Avoid main loop recursion in situations where you can’t handle arbitrary callbacks. Instead, structure your code so that you simply return to the main loop and then get called again when there is more work to do.
malloc¶
Allocates n_bytes bytes of memory.
If n_bytes is 0 it returns None.
If the allocation fails (because the system is out of memory), the program is terminated.
Parameters:
n_bytes— the number of bytes to allocate
malloc0¶
Allocates n_bytes bytes of memory, initialized to 0's.
If n_bytes is 0 it returns None.
If the allocation fails (because the system is out of memory), the program is terminated.
Parameters:
n_bytes— the number of bytes to allocate
malloc0_n¶
This function is similar to malloc0, allocating (n_blocks * n_block_bytes) bytes,
but care is taken to detect possible overflow during multiplication.
If the allocation fails (because the system is out of memory), the program is terminated.
Parameters:
n_blocks— the number of blocks to allocaten_block_bytes— the size of each block in bytes
malloc_n¶
This function is similar to malloc, allocating (n_blocks * n_block_bytes) bytes,
but care is taken to detect possible overflow during multiplication.
If the allocation fails (because the system is out of memory), the program is terminated.
Parameters:
n_blocks— the number of blocks to allocaten_block_bytes— the size of each block in bytes
markup_error_quark¶
markup_escape_text¶
Escapes text so that the markup parser will parse it verbatim. Less than, greater than, ampersand, etc. are replaced with the corresponding entities. This function would typically be used when writing out a file to be parsed with the markup parser.
Note that this function doesn't protect whitespace and line endings from being processed according to the XML rules for normalization of line endings and attribute values.
Note also that this function will produce character references in the range of ... for all control sequences except for tabstop, newline and carriage return. The character references in this range are not valid XML 1.0, but they are valid XML 1.1 and will be accepted by the GMarkup parser.
Parameters:
text— some valid UTF-8 textlength— length oftextin bytes, or -1 if the text is nul-terminated
mem_is_system_malloc¶
:::warning Deprecated since 2.46 This API is deprecated. :::
Checks whether the allocator used by malloc is the system's
malloc implementation. If it returns True memory allocated with
malloc() can be used interchangeably with memory allocated using malloc.
This function is useful for avoiding an extra copy of allocated memory returned
by a non-GLib-based API.
mem_profile¶
:::warning Deprecated since 2.46 This API is deprecated. :::
GLib used to support some tools for memory profiling, but this no longer works. There are many other useful tools for memory profiling these days which can be used instead.
mem_set_vtable¶
:::warning Deprecated since 2.46 This API is deprecated. :::
This function used to let you override the memory allocation function. However, its use was incompatible with the use of global constructors in GLib and GIO, because those use the GLib allocators before main is reached. Therefore this function is now deprecated and is just a stub.
Parameters:
vtable— table of memory allocation routines.
memdup¶
:::warning Deprecated since 2.68 This API is deprecated. :::
Allocates byte_size bytes of memory, and copies byte_size bytes into it
from mem. If mem is NULL it returns NULL.
Parameters:
mem— the memory to copybyte_size— the number of bytes to copy
memdup2¶
Allocates byte_size bytes of memory, and copies byte_size bytes into it
from mem. If mem is NULL it returns NULL.
This replaces memdup, which was prone to integer overflows when
converting the argument from a gsize to a guint.
Parameters:
mem— the memory to copybyte_size— the number of bytes to copy
mkdir¶
A wrapper for the POSIX mkdir() function. The mkdir() function attempts to create a directory with the given name and permissions. The mode argument is ignored on Windows.
See your C library manual for more details about mkdir().
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)mode— permissions to use for the newly created directory
mkdir_with_parents¶
def mkdir_with_parents(pathname: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: int) -> int
Create a directory if it doesn't already exist. Create intermediate parent directories as needed, too.
Parameters:
pathname— a pathname in the GLib file name encodingmode— permissions to use for newly created directories
nullify_pointer¶
Set the pointer at the specified location to None.
Parameters:
nullify_location— the memory address of the pointer.
number_parser_error_quark¶
on_error_query¶
Prompts the user with
[E]xit, [H]alt, show [S]tack trace or [P]roceed.
This function is intended to be used for debugging use only.
The following example shows how it can be used together with
the g_log() functions.
#include <glib.h>
static void
log_handler (const gchar *log_domain,
GLogLevelFlags log_level,
const gchar *message,
gpointer user_data)
{
g_log_default_handler (log_domain, log_level, message, user_data);
g_on_error_query (MY_PROGRAM_NAME);
}
int
main (int argc, char *argv[])
{
g_log_set_handler (MY_LOG_DOMAIN,
G_LOG_LEVEL_WARNING |
G_LOG_LEVEL_ERROR |
G_LOG_LEVEL_CRITICAL,
log_handler,
NULL);
...
If "[E]xit" is selected, the application terminates with a call to _exit(0).
If "[S]tack" trace is selected, on_error_stack_trace is called.
This invokes gdb, which attaches to the current process and shows
a stack trace. The prompt is then shown again.
If "[P]roceed" is selected, the function returns.
This function may cause different actions on non-UNIX platforms.
On Windows consider using the G_DEBUGGER environment
variable (see Running GLib Applications) and
calling on_error_stack_trace instead.
Parameters:
prg_name— the program name, needed by gdb for the "[S]tack trace" option. Ifprg_nameisNone,get_prgnameis called to get the program name (which will work correctly if gdk_init() orGtk.inithas been called)
on_error_stack_trace¶
Invokes gdb, which attaches to the current process and shows a
stack trace. Called by on_error_query when the "[S]tack trace"
option is selected. You can get the current process's program name
with get_prgname, assuming that you have called Gtk.init or
gdk_init().
This function may cause different actions on non-UNIX platforms.
When running on Windows, this function is not called by
on_error_query. If called directly, it will raise an
exception, which will crash the program. If the G_DEBUGGER environment
variable is set, a debugger will be invoked to attach and
handle that exception (see Running GLib Applications).
Parameters:
prg_name— the program name, needed by gdb for the "[S]tack trace" option, orNULLto use a default string
open¶
def open(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], flags: int, mode: int) -> int
A wrapper for the POSIX open() function. The open() function is used to convert a pathname into a file descriptor.
On POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements open() and file descriptors. The actual Win32 API for opening files is quite different, see MSDN documentation for CreateFile(). The Win32 API uses file handles, which are more randomish integers, not small integers like file descriptors.
Because file descriptors are specific to the C library on Windows, the file descriptor returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the file descriptor returned by this function cannot be passed to C library functions like write() or read().
See your C library manual for more details about open().
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)flags— as in open()mode— as in open()
option_error_quark¶
parse_debug_string¶
Parses a string containing debugging options
into a guint containing bit flags. This is used
within GDK and GTK to parse the debug options passed on the
command line or through environment variables.
If string is equal to "all", all flags are set. Any flags
specified along with "all" in string are inverted; thus,
"all,foo,bar" or "foo,bar,all" sets all flags except those
corresponding to "foo" and "bar".
If string is equal to "help", all the available keys in keys
are printed out to standard error.
Parameters:
string— a list of debug options separated by colons, spaces, or commas, orNone.keys— pointer to an array ofDebugKeywhich associate strings with bit flags.
path_get_basename¶
Gets the last component of the filename.
If file_name ends with a directory separator it gets the component
before the last slash. If file_name consists only of directory
separators (and on Windows, possibly a drive letter), a single
separator is returned. If file_name is empty, it gets ".".
Parameters:
file_name— the name of the file
path_get_dirname¶
Gets the directory components of a file name. For example, the directory
component of /usr/bin/test is /usr/bin. The directory component of /
is /.
If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.
Parameters:
file_name— the name of the file
path_is_absolute¶
Returns True if the given file_name is an absolute file name.
Note that this is a somewhat vague concept on Windows.
On POSIX systems, an absolute file name is well-defined. It always starts from the single root directory. For example "/usr/local".
On Windows, the concepts of current drive and drive-specific current directory introduce vagueness. This function interprets as an absolute file name one that either begins with a directory separator such as "\Users\tml" or begins with the root on a drive, for example "C:\Windows". The first case also includes UNC paths such as "\\myserver\docs\foo". In all cases, either slashes or backslashes are accepted.
Note that a file name relative to the current drive root does not truly specify a file uniquely over time and across processes, as the current drive is a per-process value and can be changed.
File names relative the current directory on some specific drive,
such as "D:foo/bar", are not interpreted as absolute by this
function, but they obviously are not relative to the normal current
directory as returned by getcwd() or get_current_dir
either. Such paths should be avoided, or need to be handled using
Windows-specific code.
Parameters:
file_name— a file name
path_skip_root¶
Returns a pointer into file_name after the root component,
i.e. after the "/" in UNIX or "C:\" under Windows. If file_name
is not an absolute path it returns None.
Parameters:
file_name— a file name
pattern_match_simple¶
Matches a string against a pattern given as a string.
If this
function is to be called in a loop, it’s more efficient to compile
the pattern once with PatternSpec.new and call
PatternSpec.match_string repeatedly.
Parameters:
pattern— the UTF-8 encoded patternstring— the UTF-8 encoded string to match
pointer_bit_lock¶
This is equivalent to bit_lock, but working on pointers (or other
pointer-sized values).
For portability reasons, you may only lock on the bottom 32 bits of the pointer.
While address has a volatile qualifier, this is a historical
artifact and the argument passed to it should not be volatile.
Parameters:
address— a pointer to a #gpointer-sized valuelock_bit— a bit value between 0 and 31
pointer_bit_lock_and_get¶
This is equivalent to bit_lock, but working on pointers (or other
pointer-sized values).
For portability reasons, you may only lock on the bottom 32 bits of the pointer.
Parameters:
address— a pointer to a #gpointer-sized valuelock_bit— a bit value between 0 and 31
pointer_bit_lock_mask_ptr¶
def pointer_bit_lock_mask_ptr(ptr: int | None, lock_bit: int, set: bool, preserve_mask: int, preserve_ptr: int | None = ...) -> int | None
This mangles ptr as pointer_bit_lock and pointer_bit_unlock
do.
Parameters:
ptr— the pointer to masklock_bit— the bit to set/clear. If set toG_MAXUINT, the lockbit is taken frompreserve_ptrorptr(depending onpreserve_mask).set— whether to set (lock) the bit or unset (unlock). This has no effect, iflock_bitis set toG_MAXUINT.preserve_mask— if non-zero, a bit-mask forpreserve_ptr. Thepreserve_maskbits frompreserve_ptrare set in the result. Note that thelock_bitbit will be always set according toset, regardless ofpreserve_maskandpreserve_ptr(unlesslock_bitisG_MAXUINT).preserve_ptr— ifpreserve_maskis non-zero, the bits from this pointer are set in the result.
pointer_bit_trylock¶
This is equivalent to bit_trylock, but working on pointers (or
other pointer-sized values).
For portability reasons, you may only lock on the bottom 32 bits of the pointer.
While address has a volatile qualifier, this is a historical
artifact and the argument passed to it should not be volatile.
Parameters:
address— a pointer to a #gpointer-sized valuelock_bit— a bit value between 0 and 31
pointer_bit_unlock¶
This is equivalent to bit_unlock, but working on pointers (or other
pointer-sized values).
For portability reasons, you may only lock on the bottom 32 bits of the pointer.
While address has a volatile qualifier, this is a historical
artifact and the argument passed to it should not be volatile.
Parameters:
address— a pointer to a #gpointer-sized valuelock_bit— a bit value between 0 and 31
pointer_bit_unlock_and_set¶
def pointer_bit_unlock_and_set(address: int, lock_bit: int, ptr: int | None, preserve_mask: int) -> None
This is equivalent to pointer_bit_unlock and atomically setting
the pointer value.
Note that the lock bit will be cleared from the pointer. If the unlocked
pointer that was set is not identical to ptr, an assertion fails. In other
words, ptr must have lock_bit unset. This also means, you usually can
only use this on the lowest bits.
Parameters:
address— a pointer to a #gpointer-sized valuelock_bit— a bit value between 0 and 31ptr— the new pointer value to setpreserve_mask— if non-zero, those bits of the current pointer inaddressare preserved. Note that thelock_bitbit will be always unset regardless ofptr,preserve_maskand the currently set value inaddress.
poll¶
Polls fds, as with the poll() system call, but portably. (On
systems that don't have poll(), it is emulated using select().)
This is used internally by MainContext, but it can be called
directly if you need to block until a file descriptor is ready, but
don't want to run the full main loop.
Each element of fds is a PollFD describing a single file
descriptor to poll. The fd field indicates the file descriptor,
and the events field indicates the events to poll for. On return,
the revents fields will be filled with the events that actually
occurred.
On POSIX systems, the file descriptors in fds can be any sort of
file descriptor, but the situation is much more complicated on
Windows. If you need to use poll in code that has to run on
Windows, the easiest solution is to construct all of your
GPollFDs with g_io_channel_win32_make_pollfd().
Parameters:
fds— file descriptors to pollnfds— the number of file descriptors infdstimeout— amount of time to wait, in milliseconds, or -1 to wait forever
prefix_error_literal¶
Prefixes prefix to an existing error message. If err or *err is
None (i.e.: no error variable) then do nothing.
Parameters:
err— a return location for aError, orNoneprefix— string to prefixerrwith
propagate_error¶
If dest is None, free src; otherwise, moves src into *dest.
The error variable dest points to must be None.
src must be non-None.
Note that src is no longer valid after this call. If you want
to keep using the same GError*, you need to set it to None
after calling this function on it.
Parameters:
src— error to move into the return location
qsort_with_data¶
:::warning Deprecated since 2.82 This API is deprecated. :::
This is just like the standard C qsort() function, but
the comparison routine accepts a user data argument
(like qsort_r()).
Unlike qsort(), this is guaranteed to be a stable sort (since GLib 2.32).
Parameters:
pbase— start of array to sorttotal_elems— elements in the arraysize— size of each elementcompare_func— function to compare elements
quark_from_static_string¶
Gets the GQuark identifying the given (static) string. If the
string does not currently have an associated GQuark, a new GQuark
is created, linked to the given string.
Note that this function is identical to quark_from_string except
that if a new GQuark is created the string itself is used rather
than a copy. This saves memory, but can only be used if the string
will continue to exist until the program terminates. It can be used
with statically allocated strings in the main program, but not with
statically allocated memory in dynamically loaded modules, if you
expect to ever unload the module again (e.g. do not use this
function in GTK theme engines).
This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.
Parameters:
string— a string
quark_from_string¶
Gets the GQuark identifying the given string. If the string does
not currently have an associated GQuark, a new GQuark is created,
using a copy of the string.
This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.
Parameters:
string— a string
quark_to_string¶
Gets the string associated with the given GQuark.
Parameters:
quark— aGQuark.
quark_try_string¶
Gets the GQuark associated with the given string, or 0 if string is
None or it has no associated GQuark.
If you want the GQuark to be created if it doesn't already exist,
use quark_from_string or quark_from_static_string.
This function must not be used before library constructors have finished running.
Parameters:
string— a string
random_double¶
Returns a random #gdouble equally distributed over the range [0..1).
random_double_range¶
Returns a random #gdouble equally distributed over the range
[begin..end).
Parameters:
begin— lower closed bound of the intervalend— upper open bound of the interval
random_int¶
Return a random #guint32 equally distributed over the range [0..2^32-1].
random_int_range¶
Returns a random #gint32 equally distributed over the range
[begin..end-1].
Parameters:
begin— lower closed bound of the intervalend— upper open bound of the interval
random_set_seed¶
Sets the seed for the global random number generator, which is used
by the g_random_* functions, to seed.
Parameters:
seed— a value to reinitialize the global random number generator
rc_box_acquire¶
Acquires a reference on the data pointed by mem_block.
Parameters:
mem_block— a pointer to reference counted data
rc_box_alloc¶
Allocates block_size bytes of memory, and adds reference
counting semantics to it.
The data will be freed when its reference count drops to zero.
The allocated data is guaranteed to be suitably aligned for any built-in type.
Parameters:
block_size— the size of the allocation, must be greater than 0
rc_box_alloc0¶
Allocates block_size bytes of memory, and adds reference
counting semantics to it.
The contents of the returned data is set to zero.
The data will be freed when its reference count drops to zero.
The allocated data is guaranteed to be suitably aligned for any built-in type.
Parameters:
block_size— the size of the allocation, must be greater than 0
rc_box_dup¶
Allocates a new block of data with reference counting
semantics, and copies block_size bytes of mem_block
into it.
Parameters:
block_size— the number of bytes to copy, must be greater than 0mem_block— the memory to copy
rc_box_get_size¶
Retrieves the size of the reference counted data pointed by mem_block.
Parameters:
mem_block— a pointer to reference counted data
rc_box_release¶
Releases a reference on the data pointed by mem_block.
If the reference was the last one, it will free the
resources allocated for mem_block.
Parameters:
mem_block— a pointer to reference counted data
rc_box_release_full¶
Releases a reference on the data pointed by mem_block.
If the reference was the last one, it will call clear_func
to clear the contents of mem_block, and then will free the
resources allocated for mem_block.
Parameters:
mem_block— a pointer to reference counted dataclear_func— a function to call when clearing the data
realloc¶
Reallocates the memory pointed to by mem, so that it now has space for
n_bytes bytes of memory. It returns the new address of the memory, which may
have been moved. mem may be None, in which case it's considered to
have zero-length. n_bytes may be 0, in which case None will be returned
and mem will be freed unless it is None.
If the allocation fails (because the system is out of memory), the program is terminated.
Parameters:
mem— the memory to reallocaten_bytes— new size of the memory in bytes
realloc_n¶
This function is similar to realloc, allocating (n_blocks * n_block_bytes) bytes,
but care is taken to detect possible overflow during multiplication.
If the allocation fails (because the system is out of memory), the program is terminated.
Parameters:
mem— the memory to reallocaten_blocks— the number of blocks to allocaten_block_bytes— the size of each block in bytes
ref_count_compare¶
Compares the current value of rc with val.
Parameters:
rc— the address of a reference count variableval— the value to compare
ref_count_dec¶
Decreases the reference count.
If True is returned, the reference count reached 0. After this point, rc
is an undefined state and must be reinitialized with
ref_count_init to be used again.
Parameters:
rc— the address of a reference count variable
ref_count_inc¶
Increases the reference count.
Parameters:
rc— the address of a reference count variable
ref_count_init¶
Initializes a reference count variable to 1.
ref_string_acquire¶
Acquires a reference on a string.
Parameters:
str— a reference counted string
ref_string_equal¶
Compares two ref-counted strings for byte-by-byte equality.
It can be passed to HashTable.new as the key equality function,
and behaves exactly the same as str_equal (or strcmp()), but
can return slightly faster as it can check the string lengths before checking
all the bytes.
Parameters:
str1— a reference counted stringstr2— a reference counted string
ref_string_length¶
Retrieves the length of str.
Parameters:
str— a reference counted string
ref_string_new¶
Creates a new reference counted string and copies the contents of str
into it.
Parameters:
str— a NUL-terminated string
ref_string_new_intern¶
Creates a new reference counted string and copies the content of str
into it.
If you call this function multiple times with the same str, or with
the same contents of str, it will return a new reference, instead of
creating a new string.
Parameters:
str— a NUL-terminated string
ref_string_new_len¶
Creates a new reference counted string and copies the contents of str
into it, up to len bytes.
Since this function does not stop at nul bytes, it is the caller's
responsibility to ensure that str has at least len addressable bytes.
Parameters:
str— a stringlen— length ofstrto use, or -1 ifstris nul-terminated
ref_string_release¶
Releases a reference on a string; if it was the last reference, the resources allocated by the string are freed as well.
Parameters:
str— a reference counted string
reload_user_special_dirs_cache¶
Resets the cache used for get_user_special_dir, so
that the latest on-disk version is used. Call this only
if you just changed the data on disk yourself.
Due to thread safety issues this may cause leaking of strings
that were previously returned from get_user_special_dir
that can't be freed. We ensure to only leak the data for
the directories that actually changed value though.
remove¶
A wrapper for the POSIX remove() function. The remove() function deletes a name from the filesystem.
See your C library manual for more details about how remove() works on your system. On Unix, remove() removes also directories, as it calls unlink() for files and rmdir() for directories. On Windows, although remove() in the C library only works for files, this function tries first remove() and then if that fails rmdir(), and thus works for both files and directories. Note however, that on Windows, it is in general not possible to remove a file that is open to some process, or mapped into memory.
If this function fails on Windows you can't infer too much from the errno value. rmdir() is tried regardless of what caused remove() to fail. Any errno value set by remove() will be overwritten by that set by rmdir().
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)
rename¶
def rename(oldfilename: str | bytes | os.PathLike[str] | os.PathLike[bytes], newfilename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> int
A wrapper for the POSIX rename() function. The rename() function renames a file, moving it between directories if required.
See your C library manual for more details about how rename() works on your system. It is not possible in general on Windows to rename a file that is open to some process.
Parameters:
oldfilename— a pathname in the GLib file name encoding (UTF-8 on Windows)newfilename— a pathname in the GLib file name encoding
rmdir¶
A wrapper for the POSIX rmdir() function. The rmdir() function deletes a directory from the filesystem.
See your C library manual for more details about how rmdir() works on your system.
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)
set_application_name¶
Sets a human-readable name for the application. This name should be
localized if possible, and is intended for display to the user.
Contrast with set_prgname, which sets a non-localized name.
set_prgname will be called automatically by Gtk.init,
but set_application_name will not.
Note that for thread safety reasons, this function can only be called once.
The application name will be used in contexts such as error messages, or when displaying an application's name in the task list.
Parameters:
application_name— localized name of the application
set_error_literal¶
Does nothing if err is None; if err is non-None, then *err
must be None. A new Error is created and assigned to *err.
Unlike g_set_error(), message is not a printf()-style format string.
Use this function if message contains text you don't have control over,
that could include printf() escape sequences.
Parameters:
domain— error domaincode— error codemessage— error message
set_prgname¶
Sets the name of the program. This name should not be localized,
in contrast to set_application_name.
If you are using Gio.Application the program name is set in
Gio.Application.run. In case of GDK or GTK it is set in
gdk_init(), which is called by Gtk.init and the
Gtk.Application::startup handler. By default, the program name is
found by taking the last component of argv[0].
Since GLib 2.72, this function can be called multiple times and is fully thread safe. Prior to GLib 2.72, this function could only be called once per process.
See the GTK documentation
for requirements on integrating set_prgname with GTK applications.
Parameters:
prgname— the name of the program.
setenv¶
def setenv(variable: str | bytes | os.PathLike[str] | os.PathLike[bytes], value: str | bytes | os.PathLike[str] | os.PathLike[bytes], overwrite: bool) -> bool
Sets an environment variable. On UNIX, both the variable's name and value can be arbitrary byte strings, except that the variable's name cannot contain '='. On Windows, they should be in UTF-8.
Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed.
You should be mindful of the fact that environment variable handling
in UNIX is not thread-safe, and your program may crash if one thread
calls setenv while another thread is calling getenv(). (And note
that many functions, such as gettext(), call getenv() internally.)
This function is only safe to use at the very start of your program,
before creating any other threads (or creating objects that create
worker threads of their own).
If you need to set up the environment for a child process, you can
use get_environ to get an environment array, modify that with
environ_setenv and environ_unsetenv, and then pass that
array directly to execvpe(), spawn_async, or the like.
Parameters:
variable— the environment variable to set, must not contain '='.value— the value for to set the variable to.overwrite— whether to change the variable if it already exists.
shell_error_quark¶
shell_parse_argv¶
def shell_parse_argv(command_line: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> tuple[bool, list[str]]
Parses a command line into an argument vector, in much the same way the shell would, but without many of the expansions the shell would perform (variable expansion, globs, operators, filename expansion, etc. are not supported).
The results are defined to be the same as those you would get from
a UNIX98 /bin/sh, as long as the input contains none of the
unsupported shell expansions. If the input does contain such expansions,
they are passed through literally.
Possible errors are those from the G_SHELL_ERROR domain.
In particular, if command_line is an empty string (or a string containing
only whitespace), ShellError.EMPTY_STRING will be returned. It’s
guaranteed that argvp will be a non-empty array if this function returns
successfully.
Free the returned vector with strfreev.
Parameters:
command_line— command line to parse
shell_quote¶
Quotes a string so that the shell (/bin/sh) will interpret the
quoted string to mean unquoted_string.
If you pass a filename to the shell, for example, you should first quote it with this function.
The return value must be freed with free.
The quoting style used is undefined (single or double quotes may be used).
Parameters:
unquoted_string— a literal string
shell_unquote¶
Unquotes a string as the shell (/bin/sh) would.
This function only handles quotes; if a string contains file globs, arithmetic operators, variables, backticks, redirections, or other special-to-the-shell features, the result will be different from the result a real shell would produce (the variables, backticks, etc. will be passed through literally instead of being expanded).
This function is guaranteed to succeed if applied to the result of
shell_quote. If it fails, it returns None and sets the
error.
The quoted_string need not actually contain quoted or escaped text;
shell_unquote simply goes through the string and unquotes/unescapes
anything that the shell would. Both single and double quotes are
handled, as are escapes including escaped newlines.
The return value must be freed with free.
Possible errors are in the G_SHELL_ERROR domain.
Shell quoting rules are a bit strange. Single quotes preserve the
literal string exactly. escape sequences are not allowed; not even
\' - if you want a ' in the quoted text, you have to do something
like 'foo'\''bar'. Double quotes allow $, ``,",`, and
newline to be escaped with backslash. Otherwise double quotes
preserve things literally.
Parameters:
quoted_string— shell-quoted string
slice_alloc¶
Allocates a block of memory from the libc allocator.
The block address handed out can be expected to be aligned
to at least 1 * sizeof (void*).
Since GLib 2.76 this always uses the system malloc() implementation internally.
Parameters:
block_size— the number of bytes to allocate
slice_alloc0¶
Allocates a block of memory via slice_alloc and initializes
the returned memory to 0.
Since GLib 2.76 this always uses the system malloc() implementation internally.
Parameters:
block_size— the number of bytes to allocate
slice_copy¶
Allocates a block of memory from the slice allocator
and copies block_size bytes into it from mem_block.
mem_block must be non-None if block_size is non-zero.
Since GLib 2.76 this always uses the system malloc() implementation internally.
Parameters:
block_size— the number of bytes to allocatemem_block— the memory to copy
slice_free1¶
Frees a block of memory.
The memory must have been allocated via slice_alloc or
slice_alloc0 and the block_size has to match the size
specified upon allocation. Note that the exact release behaviour
can be changed with the G_DEBUG=gc-friendly environment
variable.
If mem_block is None, this function does nothing.
Since GLib 2.76 this always uses the system free_sized() implementation internally.
Parameters:
block_size— the size of the blockmem_block— a pointer to the block to free
slice_free_chain_with_offset¶
Frees a linked list of memory blocks of structure type type.
The memory blocks must be equal-sized, allocated via
slice_alloc or slice_alloc0 and linked together by a
next pointer (similar to SList). The offset of the next
field in each block is passed as third argument.
Note that the exact release behaviour can be changed with the
G_DEBUG=gc-friendly environment variable.
If mem_chain is None, this function does nothing.
Since GLib 2.76 this always uses the system free_sized() implementation internally.
Parameters:
block_size— the size of the blocksmem_chain— a pointer to the first block of the chainnext_offset— the offset of thenextfield in the blocks
slice_get_config¶
slice_get_config_state¶
slice_set_config¶
spaced_primes_closest¶
Gets the smallest prime number from a built-in array of primes which
is larger than num. This is used within GLib to calculate the optimum
size of a HashTable.
The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.
Parameters:
num— a #guint
spawn_async¶
def spawn_async(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]], envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None = ...) -> tuple[bool, Pid]
Executes a child program asynchronously.
See spawn_async_with_pipes_and_fds for a full description; this function
simply calls the spawn_async_with_pipes without any pipes, which in turn
calls spawn_async_with_pipes_and_fds.
You should call spawn_close_pid on the returned child process
reference when you don't need it any more.
If you are writing a GTK application, and the program you are spawning is a
graphical application too, then to ensure that the spawned program opens its
windows on the right screen, you may want to use Gdk.AppLaunchContext,
Gio.AppLaunchContext, or set the DISPLAY environment variable.
Note that the returned child_pid on Windows is a handle to the child
process and not its identifier. Process handles and process identifiers
are different concepts on Windows.
Parameters:
working_directory— child's current working directory, orNoneto inherit parent'sargv— child's argument vectorenvp— child's environment, orNoneto inherit parent'sflags— flags fromSpawnFlagschild_setup— function to run in the child just beforeexec()
spawn_async_with_fds¶
def spawn_async_with_fds(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str], envp: list[str] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None, stdin_fd: int, stdout_fd: int, stderr_fd: int) -> tuple[bool, Pid]
Executes a child program asynchronously.
Identical to spawn_async_with_pipes_and_fds but with n_fds set to zero,
so no FD assignments are used.
Parameters:
working_directory— child's current working directory, orNoneto inherit parent's, in the GLib file name encodingargv— child's argument vector, in the GLib file name encoding; it must be non-empty andNone-terminatedenvp— child's environment, orNoneto inherit parent's, in the GLib file name encodingflags— flags fromSpawnFlagschild_setup— function to run in the child just beforeexec()stdin_fd— file descriptor to use for child's stdin, or-1stdout_fd— file descriptor to use for child's stdout, or-1stderr_fd— file descriptor to use for child's stderr, or-1
spawn_async_with_pipes¶
def spawn_async_with_pipes(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]], envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None = ...) -> tuple[bool, Pid, int, int, int]
Identical to spawn_async_with_pipes_and_fds but with n_fds set to zero,
so no FD assignments are used.
Parameters:
working_directory— child's current working directory, orNoneto inherit parent's, in the GLib file name encodingargv— child's argument vector, in the GLib file name encoding; it must be non-empty andNone-terminatedenvp— child's environment, orNoneto inherit parent's, in the GLib file name encodingflags— flags fromSpawnFlagschild_setup— function to run in the child just beforeexec()
spawn_async_with_pipes_and_fds¶
def spawn_async_with_pipes_and_fds(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]], envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None, stdin_fd: int, stdout_fd: int, stderr_fd: int, source_fds: list[int] | None = ..., target_fds: list[int] | None = ...) -> tuple[bool, Pid, int, int, int]
Executes a child program asynchronously (your program will not block waiting for the child to exit).
The child program is specified by the only argument that must be
provided, argv. argv should be a None-terminated array of strings,
to be passed as the argument vector for the child. The first string
in argv is of course the name of the program to execute. By default,
the name of the program must be a full path. If flags contains the
SpawnFlags.SEARCH_PATH flag, the PATH environment variable is used to
search for the executable. If flags contains the
SpawnFlags.SEARCH_PATH_FROM_ENVP flag, the PATH variable from envp
is used to search for the executable. If both the
SpawnFlags.SEARCH_PATH and SpawnFlags.SEARCH_PATH_FROM_ENVP flags are
set, the PATH variable from envp takes precedence over the
environment variable.
If the program name is not a full path and SpawnFlags.SEARCH_PATH flag
is not used, then the program will be run from the current directory
(or working_directory, if specified); this might be unexpected or even
dangerous in some cases when the current directory is world-writable.
On Windows, note that all the string or string vector arguments to
this function and the other g_spawn*() functions are in UTF-8, the
GLib file name encoding. Unicode characters that are not part of
the system codepage passed in these arguments will be correctly
available in the spawned program only if it uses wide character API
to retrieve its command line. For C programs built with Microsoft's
tools it is enough to make the program have a wmain() instead of
main(). wmain() has a wide character argument vector as parameter.
At least currently, mingw doesn't support wmain(), so if you use
mingw to develop the spawned program, it should call
g_win32_get_command_line() to get arguments in UTF-8.
On Windows the low-level child process creation API CreateProcess()
doesn't use argument vectors, but a command line. The C runtime
library's spawn*() family of functions (which spawn_async_with_pipes
eventually calls) paste the argument vector elements together into
a command line, and the C runtime startup code does a corresponding
reconstruction of an argument vector from the command line, to be
passed to main(). Complications arise when you have argument vector
elements that contain spaces or double quotes. The spawn*() functions
don't do any quoting or escaping, but on the other hand the startup
code does do unquoting and unescaping in order to enable receiving
arguments with embedded spaces or double quotes. To work around this
asymmetry, spawn_async_with_pipes will do quoting and escaping on
argument vector elements that need it before calling the C runtime
spawn() function.
The returned child_pid on Windows is a handle to the child
process, not its identifier. Process handles and process
identifiers are different concepts on Windows.
envp is a None-terminated array of strings, where each string
has the form KEY=VALUE. This will become the child's environment.
If envp is None, the child inherits its parent's environment.
flags should be the bitwise OR of any flags you want to affect the
function's behaviour. The SpawnFlags.DO_NOT_REAP_CHILD means that the
child will not automatically be reaped; you must use a child watch
(g_child_watch_add()) to be notified about the death of the child process,
otherwise it will stay around as a zombie process until this process exits.
Eventually you must call spawn_close_pid on the child_pid, in order to
free resources which may be associated with the child process. (On Unix,
using a child watch is equivalent to calling waitpid() or handling
the SIGCHLD signal manually. On Windows, calling spawn_close_pid
is equivalent to calling CloseHandle() on the process handle returned
in child_pid). See g_child_watch_add().
Open UNIX file descriptors marked as FD_CLOEXEC will be automatically
closed in the child process. SpawnFlags.LEAVE_DESCRIPTORS_OPEN means that
other open file descriptors will be inherited by the child; otherwise all
descriptors except stdin/stdout/stderr will be closed before calling exec()
in the child. SpawnFlags.SEARCH_PATH means that argv[0] need not be an
absolute path, it will be looked for in the PATH environment
variable. SpawnFlags.SEARCH_PATH_FROM_ENVP means need not be an
absolute path, it will be looked for in the PATH variable from
envp. If both SpawnFlags.SEARCH_PATH and SpawnFlags.SEARCH_PATH_FROM_ENVP
are used, the value from envp takes precedence over the environment.
SpawnFlags.CHILD_INHERITS_STDIN means that the child will inherit the parent's
standard input (by default, the child's standard input is attached to
/dev/null). SpawnFlags.STDIN_FROM_DEV_NULL explicitly imposes the default
behavior. Both flags cannot be enabled at the same time and, in both cases,
the stdin_pipe_out argument is ignored.
SpawnFlags.STDOUT_TO_DEV_NULL means that the child's standard output
will be discarded (by default, it goes to the same location as the parent's
standard output). SpawnFlags.CHILD_INHERITS_STDOUT explicitly imposes the
default behavior. Both flags cannot be enabled at the same time and, in
both cases, the stdout_pipe_out argument is ignored.
SpawnFlags.STDERR_TO_DEV_NULL means that the child's standard error
will be discarded (by default, it goes to the same location as the parent's
standard error). SpawnFlags.CHILD_INHERITS_STDERR explicitly imposes the
default behavior. Both flags cannot be enabled at the same time and, in
both cases, the stderr_pipe_out argument is ignored.
It is valid to pass the same FD in multiple parameters (e.g. you can pass
a single FD for both stdout_fd and stderr_fd, and include it in
source_fds too).
source_fds and target_fds allow zero or more FDs from this process to be
remapped to different FDs in the spawned process. If n_fds is greater than
zero, source_fds and target_fds must both be non-None and the same length.
Each FD in source_fds is remapped to the FD number at the same index in
target_fds. The source and target FD may be equal to simply propagate an FD
to the spawned process. FD remappings are processed after standard FDs, so
any target FDs which equal stdin_fd, stdout_fd or stderr_fd will overwrite
them in the spawned process.
source_fds is supported on Windows since 2.72.
SpawnFlags.FILE_AND_ARGV_ZERO means that the first element of argv is
the file to execute, while the remaining elements are the actual
argument vector to pass to the file. Normally spawn_async_with_pipes
uses argv[0] as the file to execute, and passes all of argv to the child.
child_setup and user_data are a function and user data. On POSIX
platforms, the function is called in the child after GLib has
performed all the setup it plans to perform (including creating
pipes, closing file descriptors, etc.) but before calling exec().
That is, child_setup is called just before calling exec() in the
child. Obviously actions taken in this function will only affect
the child, not the parent.
On Windows, there is no separate fork() and exec() functionality.
Child processes are created and run with a single API call,
CreateProcess(). There is no sensible thing child_setup
could be used for on Windows so it is ignored and not called.
If non-None, child_pid will on Unix be filled with the child's
process ID. You can use the process ID to send signals to the child,
or to use g_child_watch_add() (or waitpid()) if you specified the
SpawnFlags.DO_NOT_REAP_CHILD flag. On Windows, child_pid will be
filled with a handle to the child process only if you specified the
SpawnFlags.DO_NOT_REAP_CHILD flag. You can then access the child
process using the Win32 API, for example wait for its termination
with the WaitFor*() functions, or examine its exit code with
GetExitCodeProcess(). You should close the handle with CloseHandle()
or spawn_close_pid when you no longer need it.
If non-None, the stdin_pipe_out, stdout_pipe_out, stderr_pipe_out
locations will be filled with file descriptors for writing to the child's
standard input or reading from its standard output or standard error.
The caller of spawn_async_with_pipes must close these file descriptors
when they are no longer in use. If these parameters are None, the
corresponding pipe won't be created.
If stdin_pipe_out is None, the child's standard input is attached to
/dev/null unless SpawnFlags.CHILD_INHERITS_STDIN is set.
If stderr_pipe_out is NULL, the child's standard error goes to the same
location as the parent's standard error unless SpawnFlags.STDERR_TO_DEV_NULL
is set.
If stdout_pipe_out is NULL, the child's standard output goes to the same
location as the parent's standard output unless SpawnFlags.STDOUT_TO_DEV_NULL
is set.
error can be None to ignore errors, or non-None to report errors.
If an error is set, the function returns False. Errors are reported
even if they occur in the child (for example if the executable in
@argv[0] is not found). Typically the message field of returned
errors should be displayed to users. Possible errors are those from
the G_SPAWN_ERROR domain.
If an error occurs, child_pid, stdin_pipe_out, stdout_pipe_out,
and stderr_pipe_out will not be filled with valid values.
If child_pid is not None and an error does not occur then the returned
process reference must be closed using spawn_close_pid.
On modern UNIX platforms, GLib can use an efficient process launching
codepath driven internally by posix_spawn(). This has the advantage of
avoiding the fork-time performance costs of cloning the parent process
address space, and avoiding associated memory overcommit checks that are
not relevant in the context of immediately executing a distinct process.
This optimized codepath will be used provided that the following conditions
are met:
SpawnFlags.DO_NOT_REAP_CHILDis setSpawnFlags.LEAVE_DESCRIPTORS_OPENis setSpawnFlags.SEARCH_PATH_FROM_ENVPis not setworking_directoryisNonechild_setupisNone- The program is of a recognised binary format, or has a shebang. Otherwise, GLib will have to execute the program through the shell, which is not done using the optimized codepath.
If you are writing a GTK application, and the program you are spawning is a
graphical application too, then to ensure that the spawned program opens its
windows on the right screen, you may want to use Gdk.AppLaunchContext,
Gio.AppLaunchContext, or set the DISPLAY environment variable.
Parameters:
working_directory— child's current working directory, orNoneto inherit parent's, in the GLib file name encodingargv— child's argument vector, in the GLib file name encoding; it must be non-empty andNone-terminatedenvp— child's environment, orNoneto inherit parent's, in the GLib file name encodingflags— flags fromSpawnFlagschild_setup— function to run in the child just beforeexec()stdin_fd— file descriptor to use for child's stdin, or-1stdout_fd— file descriptor to use for child's stdout, or-1stderr_fd— file descriptor to use for child's stderr, or-1source_fds— array of FDs from the parent process to make available in the child processtarget_fds— array of FDs to remapsource_fdsto in the child process
spawn_check_exit_status¶
:::warning Deprecated since 2.70 This API is deprecated. :::
An old name for spawn_check_wait_status, deprecated because its
name is misleading.
Despite the name of the function, wait_status must be the wait status
as returned by spawn_sync, Gio.Subprocess.get_status, waitpid(),
etc. On Unix platforms, it is incorrect for it to be the exit status
as passed to exit() or returned by Gio.Subprocess.get_exit_status or
WEXITSTATUS().
Parameters:
wait_status— A status as returned fromspawn_sync
spawn_check_wait_status¶
Set error if wait_status indicates the child exited abnormally
(e.g. with a nonzero exit code, or via a fatal signal).
The spawn_sync and g_child_watch_add() family of APIs return the
status of subprocesses encoded in a platform-specific way.
On Unix, this is guaranteed to be in the same format waitpid() returns,
and on Windows it is guaranteed to be the result of GetExitCodeProcess().
Prior to the introduction of this function in GLib 2.34, interpreting
wait_status required use of platform-specific APIs, which is problematic
for software using GLib as a cross-platform layer.
Additionally, many programs simply want to determine whether or not
the child exited successfully, and either propagate a Error or
print a message to standard error. In that common case, this function
can be used. Note that the error message in error will contain
human-readable information about the wait status.
The domain and code of error have special semantics in the case
where the process has an "exit code", as opposed to being killed by
a signal. On Unix, this happens if WIFEXITED() would be true of
wait_status. On Windows, it is always the case.
The special semantics are that the actual exit code will be the
code set in error, and the domain will be G_SPAWN_EXIT_ERROR.
This allows you to differentiate between different exit codes.
If the process was terminated by some means other than an exit
status (for example if it was killed by a signal), the domain will be
G_SPAWN_ERROR and the code will be SpawnError.FAILED.
This function just offers convenience; you can of course also check
the available platform via a macro such as G_OS_UNIX, and use
WIFEXITED() and WEXITSTATUS() on wait_status directly. Do not attempt
to scan or parse the error message string; it may be translated and/or
change in future versions of GLib.
Prior to version 2.70, spawn_check_exit_status provides the same
functionality, although under a misleading name.
Parameters:
wait_status— A platform-specific wait status as returned fromspawn_sync
spawn_close_pid¶
On some platforms, notably Windows, the GPid type represents a resource
which must be closed to prevent resource leaking. spawn_close_pid
is provided for this purpose. It should be used on all platforms, even
though it doesn't do anything under UNIX.
Parameters:
pid— The process reference to close
spawn_command_line_async¶
def spawn_command_line_async(command_line: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> bool
A simple version of spawn_async that parses a command line with
shell_parse_argv and passes it to spawn_async.
Runs a command line in the background. Unlike spawn_async, the
SpawnFlags.SEARCH_PATH flag is enabled, other flags are not. Note
that SpawnFlags.SEARCH_PATH can have security implications, so
consider using spawn_async directly if appropriate. Possible
errors are those from shell_parse_argv and spawn_async.
The same concerns on Windows apply as for spawn_command_line_sync.
Parameters:
command_line— a command line
spawn_command_line_sync¶
def spawn_command_line_sync(command_line: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> tuple[bool, list[int], list[int], int]
A simple version of spawn_sync with little-used parameters
removed, taking a command line instead of an argument vector.
See spawn_sync for full details.
The command_line argument will be parsed by shell_parse_argv.
Unlike spawn_sync, the SpawnFlags.SEARCH_PATH flag is enabled.
Note that SpawnFlags.SEARCH_PATH can have security implications, so
consider using spawn_sync directly if appropriate.
Possible errors are those from spawn_sync and those
from shell_parse_argv.
If wait_status is non-None, the platform-specific status of
the child is stored there; see the documentation of
spawn_check_wait_status for how to use and interpret this.
On Unix platforms, note that it is usually not equal
to the integer passed to exit() or returned from main().
On Windows, please note the implications of shell_parse_argv
parsing command_line. Parsing is done according to Unix shell rules, not
Windows command interpreter rules.
Space is a separator, and backslashes are
special. Thus you cannot simply pass a command_line containing
canonical Windows paths, like "c:\program files\app\app.exe", as
the backslashes will be eaten, and the space will act as a
separator. You need to enclose such paths with single quotes, like
"'c:\program files\app\app.exe' 'e:\folder\argument.txt'".
Parameters:
command_line— a command line
spawn_error_quark¶
spawn_exit_error_quark¶
spawn_sync¶
def spawn_sync(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]], envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None = ...) -> tuple[bool, list[int], list[int], int]
Executes a child synchronously (waits for the child to exit before returning).
All output from the child is stored in standard_output and standard_error,
if those parameters are non-None. Note that you must set the
SpawnFlags.STDOUT_TO_DEV_NULL and SpawnFlags.STDERR_TO_DEV_NULL flags when
passing None for standard_output and standard_error.
If wait_status is non-None, the platform-specific status of
the child is stored there; see the documentation of
spawn_check_wait_status for how to use and interpret this.
On Unix platforms, note that it is usually not equal
to the integer passed to exit() or returned from main().
Note that it is invalid to pass SpawnFlags.DO_NOT_REAP_CHILD in
flags, and on POSIX platforms, the same restrictions as for
child_watch_source_new apply.
If an error occurs, no data is returned in standard_output,
standard_error, or wait_status.
This function calls spawn_async_with_pipes internally; see that
function for full details on the other parameters and details on
how these functions work on Windows.
Parameters:
working_directory— child's current working directory, orNoneto inherit parent'sargv— child's argument vector, which must be non-empty andNone-terminatedenvp— child's environment, orNoneto inherit parent'sflags— flags fromSpawnFlagschild_setup— function to run in the child just beforeexec()
stat¶
A wrapper for the POSIX stat() function. The stat() function
returns information about a file. On Windows the stat() function in
the C library checks only the FAT-style READONLY attribute and does
not look at the ACL at all. Thus on Windows the protection bits in
the st_mode field are a fabrication of little use.
On Windows the Microsoft C libraries have several variants of the stat struct and stat() function with names like _stat(), _stat32(), _stat32i64() and _stat64i32(). The one used here is for 32-bit code the one with 32-bit size and time fields, specifically called _stat32().
In Microsoft's compiler, by default struct stat means one with
64-bit time fields while in MinGW struct stat is the legacy one
with 32-bit fields. To hopefully clear up this messs, the gstdio.h
header defines a type StatBuf which is the appropriate struct type
depending on the platform and/or compiler being used. On POSIX it
is just struct stat, but note that even on POSIX platforms, stat()
might be a macro.
See your C library manual for more details about stat().
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)buf— a pointer to a stat struct, which will be filled with the file information
stpcpy¶
Copies a nul-terminated string into the destination buffer, including
the trailing nul byte, and returns a pointer to the trailing nul byte
in dest. The return value is useful for concatenating multiple
strings without having to repeatedly scan for the end.
Parameters:
dest— destination buffersrc— source string
str_equal¶
Compares two strings for byte-by-byte equality and returns True
if they are equal. It can be passed to g_hash_table_new() as the
key_equal_func parameter, when using non-None strings as keys in a
HashTable.
This function is typically used for hash table comparisons, but can be used
for general purpose comparisons of non-None strings. For a None-safe string
comparison function, see strcmp0.
Parameters:
v1— a keyv2— a key to compare withv1
str_has_prefix¶
Looks whether the string str begins with prefix.
Parameters:
str— a string to look inprefix— the prefix to look for
str_has_suffix¶
Looks whether a string ends with suffix.
Parameters:
str— a string to look insuffix— the suffix to look for
str_hash¶
Converts a string to a hash value.
This function implements the widely used "djb" hash apparently
posted by Daniel Bernstein to comp.lang.c some time ago. The 32
bit unsigned hash value starts at 5381 and for each byte 'c' in
the string, is updated: hash = hash * 33 + c. This function
uses the signed value of each byte.
It can be passed to g_hash_table_new() as the hash_func parameter,
when using non-None strings as keys in a HashTable.
Note that this function may not be a perfect fit for all use cases. For example, it produces some hash collisions with strings as short as 2.
Parameters:
v— a string key
str_is_ascii¶
Determines if a string is pure ASCII. A string is pure ASCII if it contains no bytes with the high bit set.
Parameters:
str— a string
str_match_string¶
Checks if a search conducted for search_term should match
potential_hit.
This function calls str_tokenize_and_fold on both
search_term and potential_hit. ASCII alternates are never taken
for search_term but will be taken for potential_hit according to
the value of accept_alternates.
A hit occurs when each folded token in search_term is a prefix of a
folded token from potential_hit.
Depending on how you're performing the search, it will typically be
faster to call g_str_tokenize_and_fold() on each string in
your corpus and build an index on the returned folded tokens, then
call g_str_tokenize_and_fold() on the search term and
perform lookups into that index.
As some examples, searching for ‘fred’ would match the potential hit ‘Smith, Fred’ and also ‘Frédéric’. Searching for ‘Fréd’ would match ‘Frédéric’ but not ‘Frederic’ (due to the one-directional nature of accent matching). Searching ‘fo’ would match ‘Foo’ and ‘Bar Foo Baz’, but not ‘SFO’ (because no word has ‘fo’ as a prefix).
Parameters:
search_term— the search term from the userpotential_hit— the text that may be a hitaccept_alternates— if true, ASCII alternates are accepted
str_to_ascii¶
Transliterate str to plain ASCII.
For best results, str should be in composed normalised form.
This function performs a reasonably good set of character replacements. The particular set of replacements that is done may change by version or even by runtime environment.
If the source language of str is known, it can used to improve the
accuracy of the translation by passing it as from_locale. It should
be a valid POSIX locale string (of the form
language[_territory][.codeset][@modifier]).
If from_locale is None then the current locale is used.
If you want to do translation for no specific locale, and you want it
to be done independently of the currently locale, specify "C" for
from_locale.
Parameters:
str— a string, in UTF-8from_locale— the source locale, if known
str_tokenize_and_fold¶
def str_tokenize_and_fold(string: str, translit_locale: str | None = ...) -> tuple[list[str], list[str]]
Tokenizes string and performs folding on each token.
A token is a non-empty sequence of alphanumeric characters in the
source string, separated by non-alphanumeric characters. An
"alphanumeric" character for this purpose is one that matches
unichar_isalnum or unichar_ismark.
Each token is then (Unicode) normalised and case-folded. If
ascii_alternates is non-NULL and some of the returned tokens
contain non-ASCII characters, ASCII alternatives will be generated.
The number of ASCII alternatives that are generated and the method
for doing so is unspecified, but translit_locale (if specified) may
improve the transliteration if the language of the source string is
known.
Parameters:
string— a string to tokenizetranslit_locale— the language code (like 'de' or 'en_GB') from whichstringoriginates
strcanon¶
For each character in string, if the character is not in valid_chars,
replaces the character with substitutor.
Modifies string in place, and return string itself, not a copy. The
return value is to allow nesting such as:
In order to modify a copy, you may use strdup:
Parameters:
string— a nul-terminated array of bytesvalid_chars— bytes permitted instringsubstitutor— replacement character for disallowed bytes
strcasecmp¶
:::warning Deprecated since 2.2 This API is deprecated. :::
A case-insensitive string comparison, corresponding to the standard
strcasecmp() function on platforms which support it.
Parameters:
s1— string to compare withs2s2— string to compare withs1
strchomp¶
Removes trailing whitespace from a string.
This function doesn't allocate or reallocate any memory;
it modifies string in place. Therefore, it cannot be used
on statically allocated strings.
The pointer to string is returned to allow the nesting of functions.
Also see strchug and GLib.strstrip.
Parameters:
string— a string to remove the trailing whitespace from
strchug¶
Removes leading whitespace from a string, by moving the rest of the characters forward.
This function doesn't allocate or reallocate any memory;
it modifies string in place. Therefore, it cannot be used on
statically allocated strings.
The pointer to string is returned to allow the nesting of functions.
Also see strchomp and GLib.strstrip.
Parameters:
string— a string to remove the leading whitespace from
strcmp0¶
Compares str1 and str2 like strcmp().
Handles NULL gracefully by sorting it before non-NULL strings.
Comparing two NULL pointers returns 0.
Parameters:
str1— a stringstr2— another string
strcompress¶
Makes a copy of a string replacing C string-style escape sequences with their one byte equivalent:
\b→ U+0008 Backspace\f→ U+000C Form Feed\n→ U+000A Line Feed\r→ U+000D Carriage Return\t→ U+0009 Horizontal Tabulation\v→ U+000B Vertical Tabulation\followed by one to three octal digits → the numeric value (mod 256)\followed by any other character → the character as is. For example,\\will turn into a backslash (\) and\"into a double quote (").
strescape does the reverse conversion.
Parameters:
source— a string to compress
strdelimit¶
Converts any delimiter characters in string to new_delimiter.
Any characters in string which are found in delimiters are
changed to the new_delimiter character. Modifies string in place,
and returns string itself, not a copy.
The return value is to allow nesting such as:
In order to modify a copy, you may use strdup:
Parameters:
string— the string to convertdelimiters— a string containing the current delimiters, orNULLto use the standard delimiters defined inSTR_DELIMITERSnew_delimiter— the new delimiter character
strdown¶
:::warning Deprecated since 2.2 This API is deprecated. :::
Converts a string to lower case.
Parameters:
string— the string to convert
strdup¶
Duplicates a string. If str is NULL it returns NULL.
Parameters:
str— the string to duplicate
strdupv¶
Copies an array of strings. The copy is a deep copy; each string is also copied.
If called on a NULL value, g_strdupv() simply returns NULL.
Parameters:
str_array— an array of strings to copy
strerror¶
Returns a string corresponding to the given error code, e.g. "no such process".
Unlike strerror(), this always returns a string in
UTF-8 encoding, and the pointer is guaranteed to remain valid for
the lifetime of the process. If the error code is unknown, it returns a
string like “Unknown error <code>”.
Note that the string may be translated according to the current locale.
The value of errno will not be changed by this function. However, it may
be changed by intermediate function calls, so you should save its value
as soon as the call returns:
Parameters:
errnum— the system error number. See the standard Cerrnodocumentation
strescape¶
It replaces the following special characters in the string source
with their corresponding C escape sequence:
| Symbol | Escape |
|---|---|
| U+0008 Backspace | \b |
| U+000C Form Feed | \f |
| U+000A Line Feed | \n |
| U+000D Carriage Return | \r |
| U+0009 Horizontal Tabulation | \t |
| U+000B Vertical Tabulation | \v |
It also inserts a backslash (\) before any backslash or a double quote (").
Additionally all characters in the range 0x01-0x1F (everything
below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are
replaced with a backslash followed by their octal representation.
Characters supplied in exceptions are not escaped.
strcompress does the reverse conversion.
Parameters:
source— a string to escapeexceptions— a string of characters not to escape insource
strfreev¶
Frees an array of strings, as well as each string it contains.
If str_array is NULL, this function simply returns.
Parameters:
str_array— an array of strings to free
strip_context¶
An auxiliary function for gettext() support (see Q_()).
Parameters:
msgid— a stringmsgval— another string
strjoinv¶
Joins an array of strings together to form one long string, with the
optional separator inserted between each of them.
If str_array has no items, the return value will be an
empty string. If str_array contains a single item, separator will not
appear in the resulting string.
Parameters:
separator— a string to insert between each of the stringsstr_array— an array of strings to join
strlcat¶
Portability wrapper that calls strlcat() on systems which have it,
and emulates it otherwise. Appends nul-terminated src string to dest,
guaranteeing nul-termination for dest. The total size of dest won't
exceed dest_size.
At most dest_size - 1 characters will be copied. Unlike strncat(),
dest_size is the full size of dest, not the space left over. This
function does not allocate memory. It always nul-terminates (unless
dest_size == 0 or there were no nul characters in the dest_size
characters of dest to start with).
Caveat: this is supposedly a more secure alternative to strcat() or
strncat(), but for real security GLib.strconcat is harder to mess up.
Parameters:
dest— destination buffer, already containing one nul-terminated stringsrc— source bufferdest_size— length ofdestbuffer in bytes (not length of existing string insidedest)
strlcpy¶
Portability wrapper that calls strlcpy() on systems which have it,
and emulates strlcpy() otherwise. Copies src to dest; dest is
guaranteed to be nul-terminated; src must be nul-terminated;
dest_size is the buffer size, not the number of bytes to copy.
At most dest_size - 1 characters will be copied. Always nul-terminates
(unless dest_size is 0). This function does not allocate memory. Unlike
strncpy(), this function doesn't pad dest (so it's often faster). It
returns the size of the attempted result, strlen (src), so if
retval >= dest_size, truncation occurred.
Caveat: strlcpy() is supposedly more secure than strcpy() or strncpy(),
but if you really want to avoid screwups, strdup is an even better
idea.
Parameters:
dest— destination buffersrc— source bufferdest_size— length ofdestin bytes
strncasecmp¶
:::warning Deprecated since 2.2 This API is deprecated. :::
A case-insensitive string comparison, corresponding to the standard
strncasecmp() function on platforms which support it. It is similar
to strcasecmp except it only compares the first n characters of
the strings.
Parameters:
s1— string to compare withs2s2— string to compare withs1n— the maximum number of characters to compare
strndup¶
Duplicates the first n bytes of a string, returning a newly-allocated
buffer n + 1 bytes long which will always be nul-terminated. If str
is less than n bytes long the buffer is padded with nuls. If str is
NULL it returns NULL.
To copy a number of characters from a UTF-8 encoded string,
use utf8_strncpy instead.
Parameters:
str— the string to duplicaten— the maximum number of bytes to copy fromstr
strnfill¶
Creates a new string length bytes long filled with fill_char.
Parameters:
length— the length of the new stringfill_char— the byte to fill the string with
strreverse¶
Reverses all of the bytes in a string. For example,
g_strreverse ("abcdef") will result in "fedcba".
Note that g_strreverse() doesn't work on UTF-8 strings
containing multibyte characters. For that purpose, use
utf8_strreverse.
Parameters:
string— the string to reverse
strrstr¶
Searches the string haystack for the last occurrence
of the string needle.
The fact that this function returns gchar * rather than const gchar * is
a historical artifact.
Parameters:
haystack— a string to search inneedle— the string to search for
strrstr_len¶
Searches the string haystack for the last occurrence
of the string needle, limiting the length of the search
to haystack_len.
The fact that this function returns gchar * rather than const gchar * is
a historical artifact.
Parameters:
haystack— a string to search inhaystack_len— the maximum length ofhaystackin bytes. A length of-1can be used to mean "search the entire string", likestrrstrneedle— the string to search for
strsignal¶
Returns a string describing the given signal, e.g. "Segmentation fault". If the signal is unknown, it returns “unknown signal (<signum>)”.
You should use this function in preference to strsignal(), because it
returns a string in UTF-8 encoding, and since not all platforms support
the strsignal() function.
Parameters:
signum— the signal number. See thesignaldocumentation
strsplit¶
Splits a string into a maximum of max_tokens pieces, using the given
delimiter. If max_tokens is reached, the remainder of string is
appended to the last token.
As an example, the result of g_strsplit (":a:bc::d:", ":", -1) is an array
containing the six strings "", "a", "bc", "", "d" and "".
As a special case, the result of splitting the empty string "" is an empty
array, not an array containing a single string. The reason for this
special case is that being able to represent an empty array is typically
more useful than consistent handling of empty elements. If you do need
to represent empty elements, you'll need to check for the empty string
before calling g_strsplit().
Parameters:
string— a string to splitdelimiter— a string which specifies the places at which to split the string. The delimiter is not included in any of the resulting strings, unlessmax_tokensis reached.max_tokens— the maximum number of pieces to splitstringinto If this is less than 1, the string is split completely
strsplit_set¶
Splits string into a number of tokens not containing any of the
bytes in delimiters.
A token is the (possibly empty) longest string that does not
contain any of the bytes in delimiters. Note that separators
will only be single bytes from delimiters. If max_tokens is reached,
the remainder is appended to the last token.
For example, the result of g_strsplit_set ("abc:def/ghi", ":/", -1)
is an array containing the three strings "abc", "def", and "ghi".
The result of g_strsplit_set (":def/ghi:/x", ":/", -1) is an array
containing the five strings "", "def", "ghi", "", "x".
As a special case, the result of splitting the empty string "" is an empty
array, not an array containing a single string. The reason for this
special case is that being able to represent an empty array is typically
more useful than consistent handling of empty elements. If you do need
to represent empty elements, you'll need to check for the empty string
before calling g_strsplit_set().
Note that this function works on bytes not characters, so it can't be used to delimit UTF-8 strings for anything but ASCII characters.
Parameters:
string— a string to splitdelimiters— a nul-terminated byte array containing bytes that are used to split the string; can be empty (just a nul byte), which will result in no string splittingmax_tokens— the maximum number of tokens to splitstringinto. If this is less than 1, the string is split completely
strstr_len¶
Searches the string haystack for the first occurrence
of the string needle, limiting the length of the search
to haystack_len or a nul terminator byte (whichever is reached first).
A length of -1 can be used to mean “search the entire string”, like
strstr().
The fact that this function returns gchar * rather than const gchar * is
a historical artifact.
Parameters:
haystack— a string to search inhaystack_len— the maximum length ofhaystackin bytes, or-1to search it entirelyneedle— the string to search for
strtod¶
Converts a string to a floating point value.
It calls the standard strtod() function to handle the conversion, but
if the string is not completely converted it attempts the conversion
again with ascii_strtod, and returns the best match.
This function should seldom be used. The normal situation when reading
numbers not for human consumption is to use ascii_strtod. Only when
you know that you must expect both locale formatted and C formatted numbers
should you use this. Make sure that you don't pass strings such as comma
separated lists of values, since the commas may be interpreted as a decimal
point in some locales, causing unexpected results.
Parameters:
nptr— the string to convert to a numeric value
strup¶
:::warning Deprecated since 2.2 This API is deprecated. :::
Converts a string to upper case.
Parameters:
string— the string to convert
strv_contains¶
Checks if an array of strings contains the string str according to
str_equal. strv must not be NULL.
Parameters:
strv— an array of strings to search instr— the string to search for
strv_equal¶
Checks if two arrays of strings contain exactly the same elements in exactly the same order.
Elements are compared using str_equal. To match independently
of order, sort the arrays first (using qsort_with_data
or similar).
Two empty arrays are considered equal. Neither strv1 nor strv2 may be
NULL.
Parameters:
strv1— an array of strings to compare tostrv2strv2— an array of strings to compare tostrv1
strv_get_type¶
strv_length¶
Returns the length of an array of strings. str_array must not be NULL.
Parameters:
str_array— an array of strings
test_add_data_func¶
Creates a new test case.
This function is similar to GLib.test_create_case.
However the test is assumed to use no fixture, and test suites are
automatically created on the fly and added to the root fixture,
based on the /-separated portions of testpath. The test_data
argument will be passed as first argument to test_func.
If testpath includes the component "subprocess" anywhere in it,
the test will be skipped by default, and only run if explicitly
required via the -p command-line option or test_trap_subprocess.
No component of testpath may start with a dot (.) if the
TEST_OPTION_ISOLATE_DIRS option is being used;
and it is recommended to do so even if it isn’t.
Parameters:
testpath— a /-separated name for the testtest_data— data for thetest_functest_func— the test function to invoke for this test
test_add_data_func_full¶
Creates a new test case.
In contrast to test_add_data_func, this function
is freeing test_data after the test run is complete.
Parameters:
testpath— a /-separated name for the testtest_data— data fortest_functest_func— the test function to invoke for this test
test_add_func¶
Creates a new test case.
This function is similar to GLib.test_create_case.
However the test is assumed to use no fixture, and test suites are
automatically created on the fly and added to the root fixture,
based on the /-separated portions of testpath.
If testpath includes the component "subprocess" anywhere in it,
the test will be skipped by default, and only run if explicitly
required via the -p command-line option or test_trap_subprocess.
No component of testpath may start with a dot (.) if the
TEST_OPTION_ISOLATE_DIRS option is being used; and
it is recommended to do so even if it isn’t.
Parameters:
testpath— a /-separated name for the testtest_func— the test function to invoke for this test
test_assert_expected_messages_internal¶
test_bug¶
Adds a message to test reports that associates a bug URI with a test case.
Bug URIs are constructed from a base URI set with test_bug_base
and bug_uri_snippet. If test_bug_base has not been called, it is
assumed to be the empty string, so a full URI can be provided to
test_bug instead.
See also test_summary.
Since GLib 2.70, the base URI is not prepended to bug_uri_snippet
if it is already a valid URI.
Parameters:
bug_uri_snippet— Bug specific bug tracker URI or URI portion.
test_bug_base¶
Specifies the base URI for bug reports.
The base URI is used to construct bug report messages for
GLib.test_message when test_bug is called.
Calling this function outside of a test case sets the
default base URI for all test cases. Calling it from within
a test case changes the base URI for the scope of the test
case only.
Bug URIs are constructed by appending a bug specific URI
portion to uri_pattern, or by replacing the special string
%s within uri_pattern if that is present.
If test_bug_base is not called, bug URIs are formed
solely from the value provided by test_bug.
Parameters:
uri_pattern— the base pattern for bug URIs
test_disable_crash_reporting¶
Attempts to disable system crash reporting infrastructure.
This function should be called before exercising code paths that are expected or intended to crash, to avoid wasting resources in system-wide crash collection infrastructure such as systemd-coredump or abrt.
test_expect_message¶
def test_expect_message(log_domain: str | None, log_level: LogLevelFlags | int, pattern: str) -> None
Indicates that a message with the given log_domain and log_level,
with text matching pattern, is expected to be logged.
When this message is logged, it will not be printed, and the test case will not abort.
This API may only be used with the old logging API (GLib.log without
G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
API. See Testing for Messages.
Use GLib.test_assert_expected_messages to assert that all
previously-expected messages have been seen and suppressed.
You can call this multiple times in a row, if multiple messages are
expected as a result of a single call. (The messages must appear in
the same order as the calls to test_expect_message.)
For example:
// g_main_context_push_thread_default() should fail if the
// context is already owned by another thread.
g_test_expect_message (G_LOG_DOMAIN,
G_LOG_LEVEL_CRITICAL,
"assertion*acquired_context*failed");
g_main_context_push_thread_default (bad_context);
g_test_assert_expected_messages ();
Note that you cannot use this to test GLib.error messages, since
GLib.error intentionally never returns even if the program doesn’t
abort; use test_trap_subprocess in this case.
If messages at LogLevelFlags.LEVEL_DEBUG are emitted, but not explicitly
expected via test_expect_message then they will be ignored.
Parameters:
log_domain— the log domain of the messagelog_level— the log level of the messagepattern— a glob-style pattern (seePatternSpec)
test_fail¶
Indicates that a test failed.
This function can be called multiple times from the same test. You can use this function if your test failed in a recoverable way.
Do not use this function if the failure of a test could cause other tests to malfunction.
Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.
If not called from inside a test, this function does nothing.
Note that unlike test_skip and test_incomplete,
this function does not log a message alongside the test failure.
If details of the test failure are available, either log them with
GLib.test_message before test_fail, or use
GLib.test_fail_printf instead.
test_failed¶
Returns whether a test has already failed.
This will be the case when test_fail,
test_incomplete or test_skip have
been called, but also if an assertion has failed.
This can be useful to return early from a test if continuing after a failed assertion might be harmful.
The return value of this function is only meaningful if it is called from inside a test function.
test_get_dir¶
Gets the pathname of the directory containing test files of the type
specified by file_type.
This is approximately the same as calling g_test_build_filename("."),
but you don't need to free the return value.
Parameters:
file_type— the type of file (built vs. distributed)
test_get_path¶
Gets the test path for the test currently being run.
In essence, it will be the same string passed as the first argument
to e.g. GLib.test_add when the test was added.
This function returns a valid string only within a test function.
Note that this is a test path, not a file system path.
test_incomplete¶
Indicates that a test failed because of some incomplete functionality.
This function can be called multiple times from the same test.
Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.
If not called from inside a test, this function does nothing.
Parameters:
msg— explanation
test_log_type_name¶
test_queue_destroy¶
Enqueues a callback destroy_func to be executed during the next test case
teardown phase.
This is most useful to auto destroy allocated test resources at the end
of a test run. Resources are released in reverse queue order, that means
enqueueing callback A before callback B will cause B() to be called
before A() during teardown.
Parameters:
destroy_func— destroy callback for teardown phasedestroy_data— destroy callback data
test_queue_free¶
Enqueues a pointer to be released with free
during the next teardown phase.
This is equivalent to calling test_queue_destroy
with a destroy callback of free.
Parameters:
gfree_pointer— the pointer to be stored
test_rand_double¶
Gets a reproducible random floating point number.
See test_rand_int for details on test case random numbers.
test_rand_double_range¶
Gets a reproducible random floating point number out of a specified range.
See test_rand_int for details on test case random numbers.
Parameters:
range_start— the minimum value returned by this functionrange_end— the minimum value not returned by this function
test_rand_int¶
Gets a reproducible random integer number.
The random numbers generated by the g_test_rand_*() family of functions change with every new test program start, unless the --seed option is given when starting test programs.
For individual test cases however, the random number generator is reseeded, to avoid dependencies between tests and to make --seed effective for all test cases.
test_rand_int_range¶
Gets a reproducible random integer number out of a specified range.
See test_rand_int for details on test case random numbers.
Parameters:
begin— the minimum value returned by this functionend— the smallest value not to be returned by this function
test_run¶
Runs all tests under the toplevel suite.
The toplevel suite can be retrieved with GLib.test_get_root.
Similar to test_run_suite, the test cases to be run are
filtered according to test path arguments (-p testpath and -s testpath)
as parsed by GLib.test_init. test_run_suite or
test_run may only be called once in a program.
In general, the tests and sub-suites within each suite are run in
the order in which they are defined. However, note that prior to
GLib 2.36, there was a bug in the g_test_add_*
functions which caused them to create multiple suites with the same
name, meaning that if you created tests "/foo/simple",
"/bar/simple", and "/foo/using-bar" in that order, they would get
run in that order (since test_run would run the first "/foo"
suite, then the "/bar" suite, then the second "/foo" suite). As of
2.36, this bug is fixed, and adding the tests in that order would
result in a running order of "/foo/simple", "/foo/using-bar",
"/bar/simple". If this new ordering is sub-optimal (because it puts
more-complicated tests before simpler ones, making it harder to
figure out exactly what has failed), you can fix it by changing the
test paths to group tests by suite in a way that will result in the
desired running order. Eg, "/simple/foo", "/simple/bar",
"/complex/foo-using-bar".
However, you should never make the actual result of a test depend
on the order that tests are run in. If you need to ensure that some
particular code runs before or after a given test case, use
GLib.test_add, which lets you specify setup and teardown functions.
If all tests are skipped or marked as incomplete (expected failures), this function will return 0 if producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.
test_run_suite¶
Executes the tests within suite and all nested test suites.
The test suites to be executed are filtered according to
test path arguments (-p testpath and -s testpath) as parsed by
GLib.test_init. See the test_run documentation
for more information on the order that tests are run in.
test_run_suite or test_run may only be
called once in a program.
Parameters:
suite— a test suite
test_set_nonfatal_assertions¶
Changes the behaviour of the various assertion macros.
The g_assert_*() macros, g_test_assert_expected_messages()
and the various g_test_trap_assert_*() macros are changed
to not abort to program.
Instead, they will call test_fail and continue.
(This also changes the behavior of test_fail so that
it will not cause the test program to abort after completing
the failed test.)
Note that the GLib.assert_not_reached and GLib.assert
macros are not affected by this.
This function can only be called after GLib.test_init.
test_skip¶
Indicates that a test was skipped.
Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.
If not called from inside a test, this function does nothing.
Parameters:
msg— explanation
test_subprocess¶
Returns true if the test program is running under test_trap_subprocess.
test_summary¶
Sets the summary for a test.
This may be included in test report output, and is useful documentation for anyone reading the source code or modifying a test in future. It must be a single line, and it should summarise what the test checks, and how.
This should be called at the top of a test function.
For example:
static void
test_array_sort (void)
{
g_test_summary ("Test my_array_sort() sorts the array correctly and stably, "
"including testing zero length and one-element arrays.");
// ...
}
See also test_bug.
Parameters:
summary— summary of the test purpose
test_timer_elapsed¶
Gets the number of seconds since the last start of the timer with
test_timer_start.
test_timer_last¶
Reports the last result of test_timer_elapsed.
test_timer_start¶
Starts a timing test.
Call test_timer_elapsed when the task is supposed
to be done. Call this function again to restart the timer.
test_trap_assertions¶
def test_trap_assertions(domain: str, file: str, line: int, func: str, assertion_flags: int, pattern: str) -> None
test_trap_fork¶
:::warning Deprecated This API is deprecated. :::
Forks the current test program to execute a test case that might not return or that might abort.
If usec_timeout is non-0, the forked test case is aborted and
considered failing if its run time exceeds it.
The forking behavior can be configured with TestTrapFlags
flags.
In the following example, the test code forks, the forked child process produces some sample output and exits successfully. The forking parent process then asserts successful child program termination and validates child program outputs.
static void
test_fork_patterns (void)
{
if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
{
g_print ("some stdout text: somagic17
");
g_printerr ("some stderr text: semagic43
");
exit (0); // successful test run
}
g_test_trap_assert_passed ();
g_test_trap_assert_stdout ("*somagic17*");
g_test_trap_assert_stderr ("*semagic43*");
}
Parameters:
usec_timeout— timeout for the forked test in microsecondstest_trap_flags— flags to modify forking behaviour
test_trap_has_passed¶
Checks the result of the last test_trap_subprocess call.
test_trap_has_skipped¶
Checks the result of the last test_trap_subprocess call.
test_trap_reached_timeout¶
Checks the result of the last test_trap_subprocess call.
test_trap_subprocess¶
def test_trap_subprocess(test_path: str | None, usec_timeout: int, test_flags: TestSubprocessFlags | int) -> None
Respawns the test program to run only test_path in a subprocess.
This is equivalent to calling test_trap_subprocess_with_envp
with envp set to NULL. See the documentation for that function
for full details.
Parameters:
test_path— test to run in a subprocessusec_timeout— timeout for the subprocess test in microseconds.test_flags— flags to modify subprocess behaviour
test_trap_subprocess_with_envp¶
def test_trap_subprocess_with_envp(test_path: str | None, envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, usec_timeout: int, test_flags: TestSubprocessFlags | int) -> None
Respawns the test program to run only test_path in a subprocess with
a given environment.
This can be used for a test case that might not return, or that might abort.
If test_path is NULL then the same test is re-run in a subprocess.
You can use test_subprocess to determine whether the test
is in a subprocess or not.
test_path can also be the name of the parent test, followed by
"/subprocess/" and then a name for the specific subtest (or just
ending with "/subprocess" if the test only has one child test);
tests with names of this form will automatically be skipped in the
parent process.
If envp is NULL, the parent process’ environment will be inherited.
If usec_timeout is non-0, the test subprocess is aborted and
considered failing if its run time exceeds it.
The subprocess behavior can be configured with TestSubprocessFlags
flags.
You can use methods such as GLib.test_trap_assert_passed,
GLib.test_trap_assert_failed, and GLib.test_trap_assert_stderr to
check the results of the subprocess. (But note that
GLib.test_trap_assert_stdout and GLib.test_trap_assert_stderr
cannot be used if test_flags specifies that the child should
inherit the parent stdout/stderr.)
If your main () needs to behave differently in the subprocess, you can
call test_subprocess (after calling GLib.test_init)
to see whether you are in a subprocess.
Internally, this function tracks the child process using
child_watch_source_new, so your process must not ignore
SIGCHLD, and must not attempt to watch or wait for the child process
via another mechanism.
The following example tests that calling my_object_new(1000000) will
abort with an error message.
static void
test_create_large_object (void)
{
if (g_test_subprocess ())
{
my_object_new (1000000);
return;
}
// Reruns this same test in a subprocess
g_test_trap_subprocess (NULL, 0, G_TEST_SUBPROCESS_DEFAULT);
g_test_trap_assert_failed ();
g_test_trap_assert_stderr ("*ERROR*too large*");
}
static void
test_different_username (void)
{
if (g_test_subprocess ())
{
// Code under test goes here
g_message ("Username is now simulated as %s", g_getenv ("USER"));
return;
}
// Reruns this same test in a subprocess
g_auto(GStrv) envp = g_get_environ ();
envp = g_environ_setenv (g_steal_pointer (&envp), "USER", "charlie", TRUE);
g_test_trap_subprocess_with_envp (NULL, envp, 0, G_TEST_SUBPROCESS_DEFAULT);
g_test_trap_assert_passed ();
g_test_trap_assert_stdout ("Username is now simulated as charlie");
}
int
main (int argc, char **argv)
{
g_test_init (&argc, &argv, NULL);
g_test_add_func ("/myobject/create-large-object",
test_create_large_object);
g_test_add_func ("/myobject/different-username",
test_different_username);
return g_test_run ();
}
Parameters:
test_path— test to run in a subprocessenvp— environment to run the test inusec_timeout— timeout for the subprocess test in microsecondstest_flags— flags to modify subprocess behaviour
timeout_add¶
Sets a function to be called at regular intervals, with the given priority.
The function is called repeatedly until it returns
SOURCE_REMOVE, at which point the timeout is automatically
destroyed and
the function will not be called again. The notify function is
called when the timeout is destroyed. The first call to the
function will be at the end of the first interval.
Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to ‘catch up’ time lost in delays).
See main loop memory management for details
on how to handle the return value and memory management of data.
This internally creates a main loop source using
timeout_source_new and attaches it to the global
MainContext using Source.attach, so the callback
will be invoked in whichever thread is running that main context. You can do
these steps manually if you need greater control or to use a custom main
context.
The interval given is in terms of monotonic time, not wall clock time.
See get_monotonic_time.
Parameters:
priority— the priority of the timeout source; typically this will be in the range betweenPRIORITY_DEFAULTandPRIORITY_HIGHinterval— the time between calls to the function, in millisecondsfunction— function to call
timeout_add_seconds¶
Sets a function to be called at regular intervals, with priority.
The function is called repeatedly until it returns SOURCE_REMOVE,
at which point the timeout is automatically destroyed and
the function will not be called again.
Unlike timeout_add, this function operates at whole second
granularity. The initial starting point of the timer is determined by the
implementation and the implementation is expected to group multiple timers
together so that they fire all at the same time. To allow this grouping,
the interval to the first timer is rounded and can deviate up to one second
from the specified interval. Subsequent timer iterations will generally run
at the specified interval.
Note that timeout functions may be delayed, due to the processing of other
event sources. Thus they should not be relied on for precise timing.
After each call to the timeout function, the time of the next
timeout is recalculated based on the current time and the given interval
See main loop memory management for details
on how to handle the return value and memory management of data.
If you want timing more precise than whole seconds, use
timeout_add instead.
The grouping of timers to fire at the same time results in a more power
and CPU efficient behavior so if your timer is in multiples of seconds
and you don’t require the first timer exactly one second from now, the
use of timeout_add_seconds is preferred over
timeout_add.
This internally creates a main loop source using
timeout_source_new_seconds and attaches it to the main loop
context using Source.attach. You can do these steps manually
if you need greater control.
It is safe to call this function from any thread.
The interval given is in terms of monotonic time, not wall clock
time. See get_monotonic_time.
Parameters:
priority— the priority of the timeout source; typically this will be in the range betweenPRIORITY_DEFAULTandPRIORITY_HIGHinterval— the time between calls to the function, in secondsfunction— function to call
timeout_source_new¶
Creates a new timeout source.
The source will not initially be associated with any MainContext
and must be added to one with Source.attach before it will be
executed.
The interval given is in terms of monotonic time, not wall clock
time. See get_monotonic_time.
Parameters:
interval— the timeout interval in milliseconds
timeout_source_new_seconds¶
Creates a new timeout source.
The source will not initially be associated with any
MainContext and must be added to one with
Source.attach before it will be executed.
The scheduling granularity/accuracy of this timeout source will be in seconds.
The interval given is in terms of monotonic time, not wall clock time.
See get_monotonic_time.
Parameters:
interval— the timeout interval in seconds
try_malloc¶
Attempts to allocate n_bytes, and returns None on failure.
Contrast with malloc, which aborts the program on failure.
Parameters:
n_bytes— number of bytes to allocate.
try_malloc0¶
Attempts to allocate n_bytes, initialized to 0's, and returns None on
failure. Contrast with malloc0, which aborts the program on failure.
Parameters:
n_bytes— number of bytes to allocate
try_malloc0_n¶
This function is similar to try_malloc0, allocating (n_blocks * n_block_bytes) bytes,
but care is taken to detect possible overflow during multiplication.
Parameters:
n_blocks— the number of blocks to allocaten_block_bytes— the size of each block in bytes
try_malloc_n¶
This function is similar to try_malloc, allocating (n_blocks * n_block_bytes) bytes,
but care is taken to detect possible overflow during multiplication.
Parameters:
n_blocks— the number of blocks to allocaten_block_bytes— the size of each block in bytes
try_realloc¶
Attempts to realloc mem to a new size, n_bytes, and returns None
on failure. Contrast with realloc, which aborts the program
on failure.
If mem is None, behaves the same as try_malloc.
Parameters:
mem— previously-allocated memory, orNone.n_bytes— number of bytes to allocate.
try_realloc_n¶
This function is similar to try_realloc, allocating (n_blocks * n_block_bytes) bytes,
but care is taken to detect possible overflow during multiplication.
Parameters:
mem— previously-allocated memory, orNone.n_blocks— the number of blocks to allocaten_block_bytes— the size of each block in bytes
ucs4_to_utf16¶
Convert a string from UCS-4 to UTF-16.
A nul character (U+0000) will be added to the result after the converted text.
Parameters:
str— a UCS-4 encoded string
ucs4_to_utf8¶
Convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8.
The result will be terminated with a nul byte.
Parameters:
str— a UCS-4 encoded string
unichar_break_type¶
Determines the break type of c. c should be a Unicode character
(to derive a character from UTF-8 encoded text, use
utf8_get_char). The break type is used to find word and line
breaks ("text boundaries"), Pango implements the Unicode boundary
resolution algorithms and normally you would use a function such
as Pango.break_ instead of caring about break types yourself.
Parameters:
c— a Unicode character
unichar_combining_class¶
Determines the canonical combining class of a Unicode character.
Parameters:
uc— a Unicode character
unichar_compose¶
Performs a single composition step of the Unicode canonical composition algorithm.
This function includes algorithmic Hangul Jamo composition,
but it is not exactly the inverse of unichar_decompose.
No composition can have either of a or b equal to zero.
To be precise, this function composes if and only if
there exists a Primary Composite P which is canonically
equivalent to the sequence <a,b>. See the Unicode
Standard for the definition of Primary Composite.
If a and b do not compose a new character, ch is set to zero.
See UAX#15 for details.
Parameters:
a— a Unicode characterb— a Unicode character
unichar_decompose¶
Performs a single decomposition step of the Unicode canonical decomposition algorithm.
This function does not include compatibility
decompositions. It does, however, include algorithmic
Hangul Jamo decomposition, as well as 'singleton'
decompositions which replace a character by a single
other character. In the case of singletons *b will
be set to zero.
If ch is not decomposable, *a is set to ch and *b
is set to zero.
Note that the way Unicode decomposition pairs are
defined, it is guaranteed that b would not decompose
further, but a may itself decompose. To get the full
canonical decomposition for ch, one would need to
recursively call this function on a. Or use
unichar_fully_decompose.
See UAX#15 for details.
Parameters:
ch— a Unicode character
unichar_digit_value¶
Determines the numeric value of a character as a decimal digit.
Parameters:
c— a Unicode character
unichar_fully_decompose¶
Computes the canonical or compatibility decomposition of a
Unicode character. For compatibility decomposition,
pass True for compat; for canonical decomposition
pass False for compat.
The decomposed sequence is placed in result. Only up to
result_len characters are written into result. The length
of the full decomposition (irrespective of result_len) is
returned by the function. For canonical decomposition,
currently all decompositions are of length at most 4, but
this may change in the future (very unlikely though).
At any rate, Unicode does guarantee that a buffer of length
18 is always enough for both compatibility and canonical
decompositions, so that is the size recommended. This is provided
as UNICHAR_MAX_DECOMPOSITION_LENGTH.
See UAX#15 for details.
Parameters:
ch— a Unicode character.compat— whether perform canonical or compatibility decompositionresult_len— length ofresult
unichar_get_mirror_char¶
In Unicode, some characters are "mirrored". This means that their images are mirrored horizontally in text that is laid out from right to left. For instance, "(" would become its mirror image, ")", in right-to-left text.
If ch has the Unicode mirrored property and there is another unicode
character that typically has a glyph that is the mirror image of ch's
glyph and mirrored_ch is set, it puts that character in the address
pointed to by mirrored_ch. Otherwise the original character is put.
Parameters:
ch— a Unicode character
unichar_get_script¶
Looks up the UnicodeScript for a particular character (as defined
by Unicode Standard Annex #24). No check is made for ch being a
valid Unicode character; if you pass in invalid character, the
result is undefined.
This function is equivalent to Pango.Script.for_unichar and the
two are interchangeable.
Parameters:
ch— a Unicode character
unichar_isalnum¶
Determines whether a character is alphanumeric.
Given some UTF-8 text, obtain a character value
with utf8_get_char.
Parameters:
c— a Unicode character
unichar_isalpha¶
Determines whether a character is alphabetic (i.e. a letter).
Given some UTF-8 text, obtain a character value with
utf8_get_char.
Parameters:
c— a Unicode character
unichar_iscntrl¶
Determines whether a character is a control character.
Given some UTF-8 text, obtain a character value with
utf8_get_char.
Parameters:
c— a Unicode character
unichar_isdefined¶
Determines if a given character is assigned in the Unicode standard.
Parameters:
c— a Unicode character
unichar_isdigit¶
Determines whether a character is numeric (i.e. a digit). This
covers ASCII 0-9 and also digits in other languages/scripts. Given
some UTF-8 text, obtain a character value with utf8_get_char.
Parameters:
c— a Unicode character
unichar_isgraph¶
Determines whether a character is printable and not a space
(returns False for control characters, format characters, and
spaces). unichar_isprint is similar, but returns True for
spaces. Given some UTF-8 text, obtain a character value with
utf8_get_char.
Parameters:
c— a Unicode character
unichar_islower¶
Determines whether a character is a lowercase letter.
Given some UTF-8 text, obtain a character value with
utf8_get_char.
Parameters:
c— a Unicode character
unichar_ismark¶
Determines whether a character is a mark (non-spacing mark,
combining mark, or enclosing mark in Unicode speak).
Given some UTF-8 text, obtain a character value
with utf8_get_char.
Note: in most cases where isalpha characters are allowed, ismark characters should be allowed to as they are essential for writing most European languages as well as many non-Latin scripts.
Parameters:
c— a Unicode character
unichar_isprint¶
Determines whether a character is printable.
Unlike unichar_isgraph, returns True for spaces.
Given some UTF-8 text, obtain a character value with
utf8_get_char.
Parameters:
c— a Unicode character
unichar_ispunct¶
Determines whether a character is punctuation or a symbol.
Given some UTF-8 text, obtain a character value with
utf8_get_char.
Parameters:
c— a Unicode character
unichar_isspace¶
Determines whether a character is a space, tab, or line separator
(newline, carriage return, etc.). Given some UTF-8 text, obtain a
character value with utf8_get_char.
(Note: don't use this to do word breaking; you have to use Pango or equivalent to get word breaking right, the algorithm is fairly complex.)
Parameters:
c— a Unicode character
unichar_istitle¶
Determines if a character is titlecase. Some characters in Unicode which are composites, such as the DZ digraph have three case variants instead of just two. The titlecase form is used at the beginning of a word where only the first letter is capitalized. The titlecase form of the DZ digraph is U+01F2 LATIN CAPITAL LETTTER D WITH SMALL LETTER Z.
Parameters:
c— a Unicode character
unichar_isupper¶
Determines if a character is uppercase.
Parameters:
c— a Unicode character
unichar_iswide¶
Determines if a character is typically rendered in a double-width cell.
Parameters:
c— a Unicode character
unichar_iswide_cjk¶
Determines if a character is typically rendered in a double-width
cell under legacy East Asian locales. If a character is wide according to
unichar_iswide, then it is also reported wide with this function, but
the converse is not necessarily true. See the
Unicode Standard Annex #11
for details.
If a character passes the unichar_iswide test then it will also pass
this test, but not the other way around. Note that some characters may
pass both this test and unichar_iszerowidth.
Parameters:
c— a Unicode character
unichar_isxdigit¶
Determines if a character is a hexadecimal digit.
Parameters:
c— a Unicode character.
unichar_iszerowidth¶
Determines if a given character typically takes zero width when rendered.
The return value is True for all non-spacing and enclosing marks
(e.g., combining accents), format characters, zero-width
space, but not U+00AD SOFT HYPHEN.
A typical use of this function is with one of unichar_iswide or
unichar_iswide_cjk to determine the number of cells a string occupies
when displayed on a grid display (terminals). However, note that not all
terminals support zero-width rendering of zero-width marks.
Parameters:
c— a Unicode character
unichar_to_utf8¶
Converts a single character to UTF-8.
Parameters:
c— a Unicode character code
unichar_tolower¶
Converts a character to lower case.
Parameters:
c— a Unicode character.
unichar_totitle¶
Converts a character to the titlecase.
Parameters:
c— a Unicode character
unichar_toupper¶
Converts a character to uppercase.
Parameters:
c— a Unicode character
unichar_type¶
Classifies a Unicode character by type.
Parameters:
c— a Unicode character
unichar_validate¶
Checks whether ch is a valid Unicode character.
Some possible integer values of ch will not be valid. U+0000 is considered a
valid character, though it’s normally a string terminator.
Parameters:
ch— a Unicode character
unichar_xdigit_value¶
Determines the numeric value of a character as a hexadecimal digit.
Parameters:
c— a Unicode character
unicode_canonical_decomposition¶
:::warning Deprecated since 2.30 This API is deprecated. :::
Computes the canonical decomposition of a Unicode character.
Parameters:
ch— a Unicode character.result_len— location to store the length of the return value.
unicode_canonical_ordering¶
Computes the canonical ordering of a string in-place. This rearranges decomposed characters in the string according to their combining classes. See the Unicode manual for more information.
Parameters:
string— a UCS-4 encoded string.
unix_closefrom¶
Close every file descriptor equal to or greater than lowfd.
Typically lowfd will be 3, to leave standard input, standard output
and standard error open.
This is the same as Linux close_range (lowfd, ~0U, 0),
but portable to other OSs and to older versions of Linux.
Equivalently, it is the same as BSD closefrom (lowfd), but portable,
and async-signal-safe on all OSs.
This function is async-signal safe, making it safe to call from a
signal handler or a SpawnChildSetupFunc, as long as lowfd is
non-negative.
See signal(7) and
signal-safety(7) for more details.
Parameters:
lowfd— Minimum fd to close, which must be non-negative
unix_error_quark¶
unix_fd_add_full¶
def unix_fd_add_full(priority: int, fd: int, condition: IOCondition | int, function: FDSourceFunc) -> int
Sets a function to be called when the IO condition, as specified by
condition becomes true for fd.
This is the same as g_unix_fd_add(), except that it allows you to
specify a non-default priority and a provide a GDestroyNotify for
user_data.
Parameters:
priority— the priority of the sourcefd— a file descriptorcondition— IO conditions to watch for onfdfunction— aGUnixFDSourceFunc
unix_fd_query_path¶
Queries the file path for the given FD opened by the current process.
Parameters:
fd— The file descriptor to query.
unix_fd_source_new¶
Creates a Source to watch for a particular I/O condition on a file
descriptor.
The source will never close the fd — you must do it yourself.
Any callback attached to the returned Source must have type
GUnixFDSourceFunc.
Parameters:
fd— a file descriptorcondition— I/O conditions to watch for onfd
unix_fdwalk_set_cloexec¶
Mark every file descriptor equal to or greater than lowfd to be closed
at the next execve() or similar, as if via the FD_CLOEXEC flag.
Typically lowfd will be 3, to leave standard input, standard output
and standard error open after exec.
This is the same as Linux close_range (lowfd, ~0U, CLOSE_RANGE_CLOEXEC),
but portable to other OSs and to older versions of Linux.
This function is async-signal safe, making it safe to call from a
signal handler or a SpawnChildSetupFunc, as long as lowfd is
non-negative.
See signal(7) and
signal-safety(7) for more details.
Parameters:
lowfd— Minimum fd to act on, which must be non-negative
unix_get_passwd_entry¶
Get the passwd file entry for the given user_name using getpwnam_r().
This can fail if the given user_name doesn’t exist.
The returned struct passwd has been allocated using malloc and should
be freed using free. The strings referenced by the returned struct are
included in the same allocation, so are valid until the struct passwd is
freed.
This function is safe to call from multiple threads concurrently.
You will need to include pwd.h to get the definition of struct passwd.
Parameters:
user_name— the username to get the passwd file entry for
unix_open_pipe¶
Similar to the UNIX pipe() call, but on modern systems like Linux uses the pipe2() system call, which atomically creates a pipe with the configured flags.
As of GLib 2.78, the supported flags are O_CLOEXEC/FD_CLOEXEC (see below)
and O_NONBLOCK. Prior to GLib 2.78, only FD_CLOEXEC was supported — if
you wanted to configure O_NONBLOCK then that had to be done separately with
fcntl().
Since GLib 2.80, the constants G_UNIX_PIPE_END_READ and
G_UNIX_PIPE_END_WRITE can be used as mnemonic indexes in fds.
It is a programmer error to call this function with unsupported flags, and a critical warning will be raised.
As of GLib 2.78, it is preferred to pass O_CLOEXEC in, rather than
FD_CLOEXEC, as that matches the underlying pipe() API more closely. Prior
to 2.78, only FD_CLOEXEC was supported. Support for FD_CLOEXEC may be
deprecated and removed in future.
Parameters:
fds— Array of two integersflags— Bitfield of file descriptor flags, as for fcntl()
unix_set_fd_nonblocking¶
Control the non-blocking state of the given file descriptor,
according to nonblock. On most systems this uses O_NONBLOCK, but
on some older ones may use O_NDELAY.
Parameters:
fd— A file descriptornonblock— IfTrue, set the descriptor to be non-blocking
unix_signal_add¶
A convenience function for g_unix_signal_source_new(), which
attaches to the default MainContext. You can remove the watch
using Source.remove.
Parameters:
priority— the priority of the signal source. Typically this will be in the range betweenPRIORITY_DEFAULTandPRIORITY_HIGH.signum— Signal numberhandler— Callback
unix_signal_source_new¶
Create a Source that will be dispatched upon delivery of the UNIX
signal signum. In GLib versions before 2.36, only SIGHUP, SIGINT,
SIGTERM can be monitored. In GLib 2.36, SIGUSR1 and SIGUSR2
were added. In GLib 2.54, SIGWINCH was added.
Note that unlike the UNIX default, all sources which have created a watch will be dispatched, regardless of which underlying thread invoked g_unix_signal_source_new().
For example, an effective use of this function is to handle SIGTERM
cleanly; flushing any outstanding files, and then calling
MainLoop.quit. It is not safe to do any of this from a regular
UNIX signal handler; such a handler may be invoked while malloc() or
another library function is running, causing reentrancy issues if the
handler attempts to use those functions. None of the GLib/GObject
API is safe against this kind of reentrancy.
The interaction of this source when combined with native UNIX functions like sigprocmask() is not defined.
The source will not initially be associated with any MainContext
and must be added to one with Source.attach before it will be
executed.
Parameters:
signum— A signal number
unlink¶
A wrapper for the POSIX unlink() function. The unlink() function deletes a name from the filesystem. If this was the last link to the file and no processes have it opened, the diskspace occupied by the file is freed.
See your C library manual for more details about unlink(). Note that on Windows, it is in general not possible to delete files that are open to some process, or mapped into memory.
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)
unsetenv¶
Removes an environment variable from the environment.
Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed.
You should be mindful of the fact that environment variable handling
in UNIX is not thread-safe, and your program may crash if one thread
calls unsetenv while another thread is calling getenv(). (And note
that many functions, such as gettext(), call getenv() internally.) This
function is only safe to use at the very start of your program, before
creating any other threads (or creating objects that create worker
threads of their own).
If you need to set up the environment for a child process, you can
use get_environ to get an environment array, modify that with
environ_setenv and environ_unsetenv, and then pass that
array directly to execvpe(), spawn_async, or the like.
Parameters:
variable— the environment variable to remove, must not contain '='
usleep¶
Pauses the current thread for the given number of microseconds.
There are 1 million microseconds per second (represented by the
USEC_PER_SEC macro). usleep may have limited precision,
depending on hardware and operating system; don't rely on the exact
length of the sleep.
Parameters:
microseconds— number of microseconds to pause
utf16_to_ucs4¶
Convert a string from UTF-16 to UCS-4.
The result will be nul-terminated.
Parameters:
str— a UTF-16 encoded string
utf16_to_utf8¶
Convert a string from UTF-16 to UTF-8.
The result will be terminated with a nul byte.
Note that the input is expected to be already in native endianness,
an initial byte-order-mark character is not handled specially.
convert can be used to convert a byte buffer of UTF-16 data of
ambiguous endianness.
Further note that this function does not validate the result string; it may (for example) include embedded nul characters. The only validation done by this function is to ensure that the input can be correctly interpreted as UTF-16, i.e. it doesn’t contain unpaired surrogates or partial character sequences.
Parameters:
str— a UTF-16 encoded string
utf8_casefold¶
Converts a string into a form that is independent of case. The
result will not correspond to any particular case, but can be
compared for equality or ordered with the results of calling
utf8_casefold on other strings.
Note that calling utf8_casefold followed by utf8_collate is
only an approximation to the correct linguistic case insensitive
ordering, though it is a fairly good one. Getting this exactly
right would require a more sophisticated collation function that
takes case sensitivity into account. GLib does not currently
provide such a function.
Parameters:
str— a UTF-8 encoded stringlen— length ofstr, in bytes, or -1 ifstris nul-terminated.
utf8_collate¶
Compares two strings for ordering using the linguistically
correct rules for the current locale.
When sorting a large number of strings, it will be significantly
faster to obtain collation keys with utf8_collate_key and
compare the keys with strcmp() when sorting instead of sorting
the original strings.
If the two strings are not comparable due to being in different collation sequences, the result is undefined. This can happen if the strings are in different language scripts, for example.
Parameters:
str1— a UTF-8 encoded stringstr2— a UTF-8 encoded string
utf8_collate_key¶
Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().
The results of comparing the collation keys of two strings
with strcmp() will always be the same as comparing the two
original keys with utf8_collate.
Note that this function depends on the current locale.
Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.
Parameters:
str— a UTF-8 encoded string.len— length ofstr, in bytes, or -1 ifstris nul-terminated.
utf8_collate_key_for_filename¶
Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().
In order to sort filenames correctly, this function treats the dot '.' as a special case. Most dictionary orderings seem to consider it insignificant, thus producing the ordering "event.c" "eventgenerator.c" "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we would like to treat numbers intelligently so that "file1" "file10" "file5" is sorted as "file1" "file5" "file10".
Note that this function depends on the current locale.
Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.
Parameters:
str— a UTF-8 encoded string.len— length ofstr, in bytes, or -1 ifstris nul-terminated.
utf8_find_next_char¶
Finds the start of the next UTF-8 character in the string after p.
p does not have to be at the beginning of a UTF-8 character. No check
is made to see if the character found is actually valid other than
it starts with an appropriate byte.
If end is NULL, the return value will never be NULL: if the end of the
string is reached, a pointer to the terminating nul byte is returned. If
end is non-NULL, the return value will be NULL if the end of the string
is reached.
Parameters:
p— a pointer to a position within a UTF-8 encoded stringend— a pointer to the byte following the end of the string, orNULLto indicate that the string is nul-terminated
utf8_find_prev_char¶
Given a position p with a UTF-8 encoded string str, find the start
of the previous UTF-8 character starting before p. Returns NULL if no
UTF-8 characters are present in str before p.
p does not have to be at the beginning of a UTF-8 character. No check
is made to see if the character found is actually valid other than
it starts with an appropriate byte.
Parameters:
str— pointer to the beginning of a UTF-8 encoded stringp— pointer to some position withinstr
utf8_get_char¶
Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
If p does not point to a valid UTF-8 encoded character, results
are undefined. If you are not sure that the bytes are complete
valid Unicode characters, you should use utf8_get_char_validated
instead.
Parameters:
p— a pointer to Unicode character encoded as UTF-8
utf8_get_char_validated¶
Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
This function checks for incomplete characters, for invalid characters such as characters that are out of the range of Unicode, and for overlong encodings of valid characters.
Note that utf8_get_char_validated returns (gunichar)-2 if
max_len is positive and any of the bytes in the first UTF-8 character
sequence are nul.
Parameters:
p— a pointer to Unicode character encoded as UTF-8max_len— the maximum number of bytes to read, or-1ifpis nul-terminated
utf8_make_valid¶
If the provided string is valid UTF-8, return a copy of it. If not, return a copy in which bytes that could not be interpreted as valid Unicode are replaced with the Unicode replacement character (U+FFFD).
For example, this is an appropriate function to use if you have received a string that was incorrectly declared to be UTF-8, and you need a valid UTF-8 version of it that can be logged or displayed to the user, with the assumption that it is close enough to ASCII or UTF-8 to be mostly readable as-is.
Parameters:
str— string to coerce into UTF-8len— the maximum length ofstrto use, in bytes. Iflenis negative, then the string is nul-terminated.
utf8_normalize¶
Converts a string into canonical form, standardizing
such issues as whether a character with an accent
is represented as a base character and combining
accent or as a single precomposed character. The
string has to be valid UTF-8, otherwise None is
returned. You should generally call utf8_normalize
before comparing two Unicode strings.
The normalization mode NormalizeMode.DEFAULT only
standardizes differences that do not affect the
text content, such as the above-mentioned accent
representation. NormalizeMode.ALL also standardizes
the "compatibility" characters in Unicode, such
as SUPERSCRIPT THREE to the standard forms
(in this case DIGIT THREE). Formatting information
may be lost but for most text operations such
characters should be considered the same.
NormalizeMode.DEFAULT_COMPOSE and NormalizeMode.ALL_COMPOSE
are like NormalizeMode.DEFAULT and NormalizeMode.ALL,
but returned a result with composed forms rather
than a maximally decomposed form. This is often
useful if you intend to convert the string to
a legacy encoding or pass it to a system with
less capable Unicode handling.
Parameters:
str— a UTF-8 encoded string.len— length ofstr, in bytes, or -1 ifstris nul-terminated.mode— the type of normalization to perform.
utf8_offset_to_pointer¶
Converts from an integer character offset to a pointer to a position within the string.
Since 2.10, this function allows to pass a negative offset to
step backwards. It is usually worth stepping backwards from the end
instead of forwards if offset is in the last fourth of the string,
since moving forward is about 3 times faster than moving backward.
Note that this function doesn’t abort when reaching the end of str.
Therefore you should be sure that offset is within string boundaries
before calling that function. Call utf8_strlen when unsure.
This limitation exists as this function is called frequently during
text rendering and therefore has to be as fast as possible.
Parameters:
str— a UTF-8 encoded stringoffset— a character offset withinstr
utf8_pointer_to_offset¶
Converts from a pointer to position within a string to an integer character offset.
Since 2.10, this function allows pos to be before str, and returns
a negative offset in this case.
Parameters:
str— a UTF-8 encoded stringpos— a pointer to a position withinstr
utf8_prev_char¶
Finds the previous UTF-8 character in the string before p.
p does not have to be at the beginning of a UTF-8 character. No check
is made to see if the character found is actually valid other than
it starts with an appropriate byte. If p might be the first
character of the string, you must use utf8_find_prev_char
instead.
Parameters:
p— a pointer to a position within a UTF-8 encoded string
utf8_strchr¶
Finds the leftmost occurrence of the given Unicode character
in a UTF-8 encoded string, while limiting the search to len bytes.
If len is -1, allow unbounded search.
Parameters:
p— a nul-terminated UTF-8 encoded stringlen— the maximum length ofpc— a Unicode character
utf8_strdown¶
Converts all Unicode characters in the string that have a case to lowercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string changing.
Parameters:
str— a UTF-8 encoded stringlen— length ofstr, in bytes, or -1 ifstris nul-terminated.
utf8_strlen¶
Computes the length of the string in characters, not including
the terminating nul character. If the max’th byte falls in the
middle of a character, the last (partial) character is not counted.
Parameters:
p— pointer to the start of a UTF-8 encoded stringmax— the maximum number of bytes to examine. Ifmaxis less than 0, then the string is assumed to be nul-terminated. Ifmaxis 0,pwill not be examined and may beNULL. Ifmaxis greater than 0, up tomaxbytes are examined
utf8_strncpy¶
Like the standard C strncpy() function, but copies a given
number of characters instead of a given number of bytes.
The src string must be valid UTF-8 encoded text. (Use
utf8_validate on all text before trying to use UTF-8 utility
functions with it.)
Note you must ensure dest is at least 4 * n + 1 to fit the
largest possible UTF-8 characters
Parameters:
dest— buffer to fill with characters fromsrcsrc— UTF-8 encoded stringn— character count
utf8_strrchr¶
Find the rightmost occurrence of the given Unicode character
in a UTF-8 encoded string, while limiting the search to len bytes.
If len is -1, allow unbounded search.
Parameters:
p— a nul-terminated UTF-8 encoded stringlen— the maximum length ofpc— a Unicode character
utf8_strreverse¶
Reverses a UTF-8 string.
str must be valid UTF-8 encoded text. (Use utf8_validate on all
text before trying to use UTF-8 utility functions with it.)
This function is intended for programmatic uses of reversed strings. It pays no attention to decomposed characters, combining marks, byte order marks, directional indicators (LRM, LRO, etc) and similar characters which might need special handling when reversing a string for display purposes.
Note that unlike strreverse, this function returns
newly-allocated memory, which should be freed with free when
no longer needed.
Parameters:
str— a UTF-8 encoded stringlen— the maximum length ofstrto use, in bytes. Iflenis negative, then the string is nul-terminated.
utf8_strup¶
Converts all Unicode characters in the string that have a case to uppercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string increasing. (For instance, the German ess-zet will be changed to SS.)
Parameters:
str— a UTF-8 encoded stringlen— length ofstr, in bytes, or -1 ifstris nul-terminated.
utf8_substring¶
Copies a substring out of a UTF-8 encoded string.
The substring will contain end_pos - start_pos characters.
Since GLib 2.72, -1 can be passed to end_pos to indicate the
end of the string.
Parameters:
str— a UTF-8 encoded stringstart_pos— a character offset withinstrend_pos— another character offset withinstr, or-1to indicate the end of the string
utf8_to_ucs4¶
Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4.
A trailing nul character (U+0000) will be added to the string after the converted text.
Parameters:
str— a UTF-8 encoded stringlen— the maximum length ofstrto use, in bytes. Iflenis negative, then the string is nul-terminated.
utf8_to_ucs4_fast¶
Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4, assuming valid UTF-8 input.
This function is roughly twice as fast as utf8_to_ucs4
but does no error checking on the input. A trailing nul character (U+0000)
will be added to the string after the converted text.
Parameters:
str— a UTF-8 encoded stringlen— the maximum length ofstrto use, in bytes. Iflenis negative, then the string is nul-terminated.
utf8_to_utf16¶
Convert a string from UTF-8 to UTF-16.
A nul character (U+0000) will be added to the result after the converted text.
Parameters:
str— a UTF-8 encoded stringlen— the maximum length (number of bytes) ofstrto use. Iflenis negative, then the string is nul-terminated.
utf8_truncate_middle¶
Cuts off the middle of the string, preserving half of truncate_length
characters at the beginning and half at the end.
If string is already short enough, this returns a copy of string.
If truncate_length is 0, an empty string is returned.
Parameters:
string— a nul-terminated UTF-8 encoded stringtruncate_length— the new size ofstring, in characters, including the ellipsis character
utf8_validate¶
Validates UTF-8 encoded text.
str is the text to validate; if str is nul-terminated, then max_len can be
-1, otherwise max_len should be the number of bytes to validate.
If end is non-NULL, then the end of the valid range will be stored there.
This is the first byte of the first invalid character if some bytes were
invalid, or the end of the text being validated otherwise — either the
trailing nul byte, or the first byte beyond max_len (if it’s positive).
Note that g_utf8_validate() returns FALSE if max_len is positive and
any of the max_len bytes are nul.
Returns TRUE if all of str was valid. Many GLib and GTK
routines require valid UTF-8 as input; so data read from a file
or the network should be checked with g_utf8_validate() before
doing anything else with it.
Parameters:
str— a pointer to character data
utf8_validate_len¶
Validates UTF-8 encoded text.
As with utf8_validate, but max_len must be set, and hence this
function will always return FALSE if any of the bytes of str are nul.
Parameters:
str— a pointer to character data
utime¶
def utime(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], utb: int | None = ...) -> int
A wrapper for the POSIX utime() function. The utime() function sets the access and modification timestamps of a file.
See your C library manual for more details about how utime() works on your system.
Parameters:
filename— a pathname in the GLib file name encoding (UTF-8 on Windows)utb— a pointer to a struct utimbuf.
uuid_string_is_valid¶
Parses the string str and verify if it is a UUID.
The function accepts the following syntax:
- simple forms (e.g.
f81d4fae-7dec-11d0-a765-00a0c91e6bf6)
Note that hyphens are required within the UUID string itself, as per the aforementioned RFC.
Parameters:
str— a string representing a UUID
uuid_string_random¶
Generates a random UUID (RFC 4122 version 4) as a string. It has the same
randomness guarantees as Rand, so must not be used for cryptographic
purposes such as key generation, nonces, salts or one-time pads.
variant_get_gtype¶
Enumerations¶
AsciiType¶
Bit flags.
ALNUM=1ALPHA=2CNTRL=4DIGIT=8GRAPH=16LOWER=32PRINT=64PUNCT=128SPACE=256UPPER=512XDIGIT=1024
BookmarkFileError¶
Enumeration.
INVALID_URI=0— URI was ill-formedINVALID_VALUE=1— a requested field was not foundAPP_NOT_REGISTERED=2— a requested application did not register a bookmarkURI_NOT_FOUND=3— a requested URI was not foundREAD=4— document was ill formedUNKNOWN_ENCODING=5— the text being parsed was in an unknown encodingWRITE=6— an error occurred while writingFILE_NOT_FOUND=7— requested file was not found
ChecksumType¶
Enumeration.
MD5=0— Use the MD5 hashing algorithmSHA1=1— Use the SHA-1 hashing algorithmSHA256=2— Use the SHA-256 hashing algorithmSHA512=3— Use the SHA-512 hashing algorithm (Since: 2.36)SHA384=4— Use the SHA-384 hashing algorithm (Since: 2.51)
ConvertError¶
Enumeration.
NO_CONVERSION=0— Conversion between the requested character sets is not supported.ILLEGAL_SEQUENCE=1— Invalid byte sequence in conversion input; or the character sequence could not be represented in the target character set.FAILED=2— Conversion failed for some reason.PARTIAL_INPUT=3— Partial character sequence at end of input.BAD_URI=4— URI is invalid.NOT_ABSOLUTE_PATH=5— Pathname is not an absolute path.NO_MEMORY=6— No memory available. Since: 2.40EMBEDDED_NUL=7— An embedded NUL character is present in conversion output where a NUL-terminated string is expected. Since: 2.56
DateDMY¶
Enumeration.
DAY=0— a dayMONTH=1— a monthYEAR=2— a year
DateMonth¶
Enumeration.
BAD_MONTH=0— invalid valueJANUARY=1— JanuaryFEBRUARY=2— FebruaryMARCH=3— MarchAPRIL=4— AprilMAY=5— MayJUNE=6— JuneJULY=7— JulyAUGUST=8— AugustSEPTEMBER=9— SeptemberOCTOBER=10— OctoberNOVEMBER=11— NovemberDECEMBER=12— December
DateWeekday¶
Enumeration.
BAD_WEEKDAY=0— invalid valueMONDAY=1— MondayTUESDAY=2— TuesdayWEDNESDAY=3— WednesdayTHURSDAY=4— ThursdayFRIDAY=5— FridaySATURDAY=6— SaturdaySUNDAY=7— Sunday
ErrorType¶
Enumeration.
UNKNOWN=0— unknown errorUNEXP_EOF=1— unexpected end of fileUNEXP_EOF_IN_STRING=2— unterminated string constantUNEXP_EOF_IN_COMMENT=3— unterminated commentNON_DIGIT_IN_CONST=4— non-digit character in a numberDIGIT_RADIX=5— digit beyond radix in a numberFLOAT_RADIX=6— non-decimal floating point numberFLOAT_MALFORMED=7— malformed floating point number
FileError¶
Enumeration.
EXIST=0— Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.ISDIR=1— File is a directory; you cannot open a directory for writing, or create or remove hard links to it.ACCES=2— Permission denied; the file permissions do not allow the attempted operation.NAMETOOLONG=3— Filename too long.NOENT=4— No such file or directory. This is a "file doesn't exist" error for ordinary files that are referenced in contexts where they are expected to already exist.NOTDIR=5— A file that isn't a directory was specified when a directory is required.NXIO=6— No such device or address. The system tried to use the device represented by a file you specified, and it couldn't find the device. This can mean that the device file was installed incorrectly, or that the physical device is missing or not correctly attached to the computer.NODEV=7— The underlying file system of the specified file does not support memory mapping.ROFS=8— The directory containing the new link can't be modified because it's on a read-only file system.TXTBSY=9— Text file busy.FAULT=10— You passed in a pointer to bad memory. (GLib won't reliably return this, don't pass in pointers to bad memory.)LOOP=11— Too many levels of symbolic links were encountered in looking up a file name. This often indicates a cycle of symbolic links.NOSPC=12— No space left on device; write operation on a file failed because the disk is full.NOMEM=13— No memory available. The system cannot allocate more virtual memory because its capacity is full.MFILE=14— The current process has too many files open and can't open any more. Duplicate descriptors do count toward this limit.NFILE=15— There are too many distinct file openings in the entire system.BADF=16— Bad file descriptor; for example, I/O on a descriptor that has been closed or reading from a descriptor open only for writing (or vice versa).INVAL=17— Invalid argument. This is used to indicate various kinds of problems with passing the wrong argument to a library function.PIPE=18— Broken pipe; there is no process reading from the other end of a pipe. Every library function that returns this error code also generates a 'SIGPIPE' signal; this signal terminates the program if not handled or blocked. Thus, your program will never actually see this code unless it has handled or blocked 'SIGPIPE'.AGAIN=19— Resource temporarily unavailable; the call might work if you try again later.INTR=20— Interrupted function call; an asynchronous signal occurred and prevented completion of the call. When this happens, you should try the call again.IO=21— Input/output error; usually used for physical read or write errors. i.e. the disk or other physical device hardware is returning errors.PERM=22— Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.NOSYS=23— Function not implemented; this indicates that the system is missing some functionality.FAILED=24— Does not correspond to a UNIX error code; this is the standard "failed for unspecified reason" error code present in allErrorerror code enumerations. Returned if no specific code applies.
FileSetContentsFlags¶
Bit flags.
NONE=0— No guarantees about file consistency or durability. The most dangerous setting, which is slightly faster than other settings.CONSISTENT=1— Guarantee file consistency: after a crash, either the old version of the file or the new version of the file will be available, but not a mixture. On Unix systems this equates to anfsync()on the file and use of an atomicrename()of the new version of the file over the old.DURABLE=2— Guarantee file durability: after a crash, the new version of the file will be available. On Unix systems this equates to anfsync()on the file (ifFileSetContentsFlags.CONSISTENTis unset), or the effects ofFileSetContentsFlags.CONSISTENTplus anfsync()on the directory containing the file after callingrename().ONLY_EXISTING=4— Only apply consistency and durability guarantees if the file already exists. This may speed up file operations if the file doesn’t currently exist, but may result in a corrupted version of the new file if the system crashes while writing it.
FileTest¶
Bit flags.
IS_REGULAR=1—Trueif the file is a regular file (not a directory). Note that this test will also returnTrueif the tested file is a symlink to a regular file.IS_SYMLINK=2—Trueif the file is a symlink.IS_DIR=4—Trueif the file is a directory.IS_EXECUTABLE=8—Trueif the file is executable.EXISTS=16—Trueif the file exists. It may or may not be a regular file.
FormatSizeFlags¶
Bit flags.
DEFAULT=0— behave the same asformat_sizeLONG_FORMAT=1— include the exact number of bytes as part of the returned string. For example, "45.6 kB (45,612 bytes)".IEC_UNITS=2— use IEC (base 1024) units with "KiB"-style suffixes. IEC units should only be used for reporting things with a strong "power of 2" basis, like RAM sizes or RAID stripe sizes. Network and storage sizes should be reported in the normal SI units.BITS=4— set the size as a quantity in bits, rather than bytes, and return units in bits. For example, ‘Mbit’ rather than ‘MB’.ONLY_VALUE=8— return only value, without unit; this should not be used together withG_FORMAT_SIZE_LONG_FORMATnorG_FORMAT_SIZE_ONLY_UNIT. Since: 2.74ONLY_UNIT=16— return only unit, without value; this should not be used together withG_FORMAT_SIZE_LONG_FORMATnorG_FORMAT_SIZE_ONLY_VALUE. Since: 2.74
HookFlagMask¶
Bit flags.
ACTIVE=1— set if the hook has not been destroyedIN_CALL=2— set if the hook is currently being runRESERVED1=4
IOChannelError¶
Enumeration.
FBIG=0— File too large.INVAL=1— Invalid argument.IO=2— IO error.ISDIR=3— File is a directory.NOSPC=4— No space left on device.NXIO=5— No such device or address.OVERFLOW=6— Value too large for defined datatype.PIPE=7— Broken pipe.FAILED=8— Some other error.
IOCondition¶
Bit flags.
IN=1— There is data to read.OUT=4— Data can be written (without blocking).PRI=2— There is urgent data to read.ERR=8— Error condition.HUP=16— Hung up (the connection has been broken, usually for pipes and sockets).NVAL=32— Invalid request. The file descriptor is not open.
IOError¶
Enumeration.
NONE=0— no errorAGAIN=1— an EAGAIN error occurredINVAL=2— an EINVAL error occurredUNKNOWN=3— another error occurred
IOFlags¶
Bit flags.
NONE=0— no special flags set. Since: 2.74APPEND=1— turns on append mode, corresponds toO_APPEND(see the documentation of the UNIX open() syscall)NONBLOCK=2— turns on nonblocking mode, corresponds toO_NONBLOCK/O_NDELAY(see the documentation of the UNIX open() syscall)IS_READABLE=4— indicates that the io channel is readable. This flag cannot be changed.IS_WRITABLE=8— indicates that the io channel is writable. This flag cannot be changed.IS_WRITEABLE=8— a misspelled version ofG_IO_FLAG_IS_WRITABLEthat existed before the spelling was fixed in GLib 2.30. It is kept here for compatibility reasons. Deprecated since 2.30IS_SEEKABLE=16— indicates that the io channel is seekable, i.e. thatIOChannel.seek_positioncan be used on it. This flag cannot be changed.MASK=31— the mask that specifies all the valid flags.GET_MASK=31— the mask of the flags that are returned fromIOChannel.get_flagsSET_MASK=3— the mask of the flags that the user can modify withIOChannel.set_flags
IOStatus¶
Enumeration.
ERROR=0— An error occurred.NORMAL=1— Success.EOF=2— End of file.AGAIN=3— Resource temporarily unavailable.
KeyFileError¶
Enumeration.
UNKNOWN_ENCODING=0— the text being parsed was in an unknown encodingPARSE=1— document was ill-formedNOT_FOUND=2— the file was not foundKEY_NOT_FOUND=3— a requested key was not foundGROUP_NOT_FOUND=4— a requested group was not foundINVALID_VALUE=5— a value could not be parsed
KeyFileFlags¶
Bit flags.
NONE=0— No flags, default behaviourKEEP_COMMENTS=1— Use this flag if you plan to write the (possibly modified) contents of the key file back to a file; otherwise all comments will be lost when the key file is written back.KEEP_TRANSLATIONS=2— Use this flag if you plan to write the (possibly modified) contents of the key file back to a file; otherwise only the translations for the current language will be written back.
LogLevelFlags¶
Bit flags.
FLAG_RECURSION=1— internal flagFLAG_FATAL=2— internal flagLEVEL_ERROR=4— log level for errors, seeGLib.error. This level is also used for messages produced byGLib.assert.LEVEL_CRITICAL=8— log level for critical warning messages, seeGLib.critical. This level is also used for messages produced byGLib.return_if_failandGLib.return_val_if_fail.LEVEL_WARNING=16— log level for warnings, seeGLib.warningLEVEL_MESSAGE=32— log level for messages, seeGLib.messageLEVEL_INFO=64— log level for informational messages, seeGLib.infoLEVEL_DEBUG=128— log level for debug messages, seeGLib.debugLEVEL_MASK=-4— a mask including all log levels
LogWriterOutput¶
Enumeration.
HANDLED=1— Log writer has handled the log entry.UNHANDLED=0— Log writer could not handle the log entry.
MainContextFlags¶
Bit flags.
NONE=0— Default behaviour.OWNERLESS_POLLING=1— Assume that polling for events will free the thread to process other jobs. That's useful if you're usingg_main_context_{prepare,query,check,dispatch}to integrate GMainContext in other event loops.
MarkupCollectType¶
Bit flags.
INVALID=0— used to terminate the list of attributes to collectSTRING=1— collect the string pointer directly from the attribute_values[] array. Expects a parameter of type (const char **). IfMarkupCollectType.OPTIONALis specified and the attribute isn't present then the pointer will be set toNoneSTRDUP=2— as withMarkupCollectType.STRING, but expects a parameter of type (char **) andstrdups the returned pointer. The pointer must be freed withfreeBOOLEAN=3— expects a parameter of type (gboolean *) and parses the attribute value as a boolean. SetsFalseif the attribute isn't present. Valid boolean values consist of (case-insensitive) "false", "f", "no", "n", "0" and "true", "t", "yes", "y", "1"TRISTATE=4— as withMarkupCollectType.BOOLEAN, but in the case of a missing attribute a value is set that compares equal to neitherFalsenorTrueMarkupCollectType.OPTIONALis impliedOPTIONAL=65536— can be bitwise ORed with the other fields. If present, allows the attribute not to appear. A default value is set depending on what value type is used
MarkupError¶
Enumeration.
BAD_UTF8=0— text being parsed was not valid UTF-8EMPTY=1— document contained nothing, or only whitespacePARSE=2— document was ill-formedUNKNOWN_ELEMENT=3— error should be set byMarkupParserfunctions; element wasn't knownUNKNOWN_ATTRIBUTE=4— error should be set byMarkupParserfunctions; attribute wasn't knownINVALID_CONTENT=5— error should be set byMarkupParserfunctions; content was invalidMISSING_ATTRIBUTE=6— error should be set byMarkupParserfunctions; a required attribute was missing
MarkupParseFlags¶
Bit flags.
DEFAULT_FLAGS=0— No special behaviour. Since: 2.74DO_NOT_USE_THIS_UNSUPPORTED_FLAG=1— flag you should not useTREAT_CDATA_AS_TEXT=2— When this flag is set, CDATA marked sections are not passed literally to thepassthroughfunction of the parser. Instead, the content of the section (without the<![CDATA[and]]>) is passed to thetextfunction. This flag was added in GLib 2.12PREFIX_ERROR_POSITION=4— Normally errors caught by GMarkup itself have line/column information prefixed to them to let the caller know the location of the error. When this flag is set the location information is also prefixed to errors generated by theMarkupParserimplementation functionsIGNORE_QUALIFIED=8— Ignore (don't report) qualified attributes and tags, along with their contents. A qualified attribute or tag is one that contains ':' in its name (ie: is in another namespace). Since: 2.40.
NormalizeMode¶
Enumeration.
DEFAULT=0— standardize differences that do not affect the text content, such as the above-mentioned accent representationNFD=0— another name forNormalizeMode.DEFAULTDEFAULT_COMPOSE=1— likeNormalizeMode.DEFAULT, but with composed forms rather than a maximally decomposed formNFC=1— another name forNormalizeMode.DEFAULT_COMPOSEALL=2— beyondNormalizeMode.DEFAULTalso standardize the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the sameNFKD=2— another name forNormalizeMode.ALLALL_COMPOSE=3— likeNormalizeMode.ALL, but with composed forms rather than a maximally decomposed formNFKC=3— another name forNormalizeMode.ALL_COMPOSE
NumberParserError¶
Enumeration.
INVALID=0— string was not a valid numberOUT_OF_BOUNDS=1— string was a number, but out of bounds
OnceStatus¶
Enumeration.
NOTCALLED=0— the function has not been called yet.PROGRESS=1— the function call is currently in progress.READY=2— the function has been called.
OptionArg¶
Enumeration.
NONE=0— No extra argument. This is useful for simple flags or booleans.STRING=1— The option takes a UTF-8 string argument.INT=2— The option takes an integer argument.CALLBACK=3— The option provides a callback (of typeGOptionArgFunc) to parse the extra argument.FILENAME=4— The option takes a filename as argument, which will be in the GLib filename encoding rather than UTF-8.STRING_ARRAY=5— The option takes a string argument, multiple uses of the option are collected into an array of strings.FILENAME_ARRAY=6— The option takes a filename as argument, multiple uses of the option are collected into an array of strings.DOUBLE=7— The option takes a double argument. The argument can be formatted either for the user's locale or for the "C" locale. Since 2.12INT64=8— The option takes a 64-bit integer. LikeOptionArg.INTbut for larger numbers. The number can be in decimal base, or in hexadecimal (when prefixed with0x, for example,0xffffffff). Since 2.12
OptionError¶
Enumeration.
UNKNOWN_OPTION=0— An option was not known to the parser. This error will only be reported, if the parser hasn't been instructed to ignore unknown options, seeOptionContext.set_ignore_unknown_options.BAD_VALUE=1— A value couldn't be parsed.FAILED=2— AGOptionArgFunccallback failed.
OptionFlags¶
Bit flags.
NONE=0— No flags.HIDDEN=1— The option doesn't appear in--helpoutput.IN_MAIN=2— The option appears in the main section of the--helpoutput, even if it is defined in a group.REVERSE=4— For options of theOptionArg.NONEkind, this flag indicates that the sense of the option is reversed. i.e.Falsewill be stored into the argument rather thanTrue.NO_ARG=8— For options of theOptionArg.CALLBACKkind, this flag indicates that the callback does not take any argument (like aOptionArg.NONEoption). Since 2.8FILENAME=16— For options of theOptionArg.CALLBACKkind, this flag indicates that the argument should be passed to the callback in the GLib filename encoding rather than UTF-8. Since 2.8OPTIONAL_ARG=32— For options of theOptionArg.CALLBACKkind, this flag indicates that the argument supply is optional. If no argument is given then data ofGOptionParseFuncwill be set to NULL. Since 2.8NOALIAS=64— This flag turns off the automatic conflict resolution which prefixes long option names withgroupname-if there is a conflict. This option should only be used in situations where aliasing is necessary to model some legacy commandline interface. It is not safe to use this option, unless all option groups are under your direct control. Since 2.8.DEPRECATED=128— This flag marks the option as deprecated in the--help. You should update the description of the option to describe what the user should do in response to the deprecation, for instance: remove the option, or replace it with another one.
RegexCompileFlags¶
Bit flags.
DEFAULT=0— No special options set. Since: 2.74CASELESS=1— Letters in the pattern match both upper- and lowercase letters. This option can be changed within a pattern by a "(?i)" option setting.MULTILINE=2— By default, GRegex treats the strings as consisting of a single line of characters (even if it actually contains newlines). The "start of line" metacharacter ("^") matches only at the start of the string, while the "end of line" metacharacter ("$") matches only at the end of the string, or before a terminating newline (unlessRegexCompileFlags.DOLLAR_ENDONLYis set). WhenRegexCompileFlags.MULTILINEis set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the string, respectively, as well as at the very start and end. This can be changed within a pattern by a "(?m)" option setting.DOTALL=4— A dot metacharacter (".") in the pattern matches all characters, including newlines. Without it, newlines are excluded. This option can be changed within a pattern by a ("?s") option setting.EXTENDED=8— Whitespace data characters in the pattern are totally ignored except when escaped or inside a character class. Whitespace does not include the VT character (code 11). In addition, characters between an unescaped "#" outside a character class and the next newline character, inclusive, are also ignored. This can be changed within a pattern by a "(?x)" option setting.ANCHORED=16— The pattern is forced to be "anchored", that is, it is constrained to match only at the first matching point in the string that is being searched. This effect can also be achieved by appropriate constructs in the pattern itself such as the "^" metacharacter.DOLLAR_ENDONLY=32— A dollar metacharacter ("$") in the pattern matches only at the end of the string. Without this option, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This option is ignored ifRegexCompileFlags.MULTILINEis set.UNGREEDY=512— Inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It can also be set by a "(?U)" option setting within the pattern.RAW=2048— Usually strings must be valid UTF-8 strings, using this flag they are considered as a raw sequence of bytes.NO_AUTO_CAPTURE=4096— Disables the use of numbered capturing parentheses in the pattern. Any opening parenthesis that is not followed by "?" behaves as if it were followed by "?:" but named parentheses can still be used for capturing (and they acquire numbers in the usual way).OPTIMIZE=8192— Since 2.74 and the port to pcre2, requests JIT compilation, which, if the just-in-time compiler is available, further processes a compiled pattern into machine code that executes much faster. However, it comes at the cost of extra processing before the match is performed, so it is most beneficial to use this when the same compiled pattern is used for matching many times. Before 2.74 this option used the built-in non-JIT optimizations in pcre1.FIRSTLINE=262144— Limits an unanchored pattern to match before (or at) the first newline. Since: 2.34DUPNAMES=524288— Names used to identify capturing subpatterns need not be unique. This can be helpful for certain types of pattern when it is known that only one instance of the named subpattern can ever be matched.NEWLINE_CR=1048576— Usually any newline character or character sequence is recognized. If this option is set, the only recognized newline character is '\r'.NEWLINE_LF=2097152— Usually any newline character or character sequence is recognized. If this option is set, the only recognized newline character is '\n'.NEWLINE_RESERVED1=4194304
RegexError¶
Enumeration.
COMPILE=0— Compilation of the regular expression failed.OPTIMIZE=1— Optimization of the regular expression failed.REPLACE=2— Replacement failed due to an ill-formed replacement string.MATCH=3— The match process failed.INTERNAL=4— Internal error of the regular expression engine. Since 2.16STRAY_BACKSLASH=101— "\" at end of pattern. Since 2.16MISSING_CONTROL_CHAR=102— "\c" at end of pattern. Since 2.16UNRECOGNIZED_ESCAPE=103— Unrecognized character follows "\". Since 2.16QUANTIFIERS_OUT_OF_ORDER=104— Numbers out of order in "{}" quantifier. Since 2.16QUANTIFIER_TOO_BIG=105— Number too big in "{}" quantifier. Since 2.16UNTERMINATED_CHARACTER_CLASS=106— Missing terminating "]" for character class. Since 2.16INVALID_ESCAPE_IN_CHARACTER_CLASS=107— Invalid escape sequence in character class. Since 2.16RANGE_OUT_OF_ORDER=108— Range out of order in character class. Since 2.16NOTHING_TO_REPEAT=109— Nothing to repeat. Since 2.16UNRECOGNIZED_CHARACTER=112— Unrecognized character after "(?", "(?<" or "(?P". Since 2.16POSIX_NAMED_CLASS_OUTSIDE_CLASS=113— POSIX named classes are supported only within a class. Since 2.16UNMATCHED_PARENTHESIS=114— Missing terminating ")" or ")" without opening "(". Since 2.16INEXISTENT_SUBPATTERN_REFERENCE=115— Reference to non-existent subpattern. Since 2.16UNTERMINATED_COMMENT=118— Missing terminating ")" after comment. Since 2.16EXPRESSION_TOO_LARGE=120— Regular expression too large. Since 2.16MEMORY_ERROR=121— Failed to get memory. Since 2.16VARIABLE_LENGTH_LOOKBEHIND=125— Lookbehind assertion is not fixed length. Since 2.16MALFORMED_CONDITION=126— Malformed number or name after "(?(". Since 2.16TOO_MANY_CONDITIONAL_BRANCHES=127— Conditional group contains more than two branches. Since 2.16ASSERTION_EXPECTED=128— Assertion expected after "(?(". Since 2.16UNKNOWN_POSIX_CLASS_NAME=130— Unknown POSIX class name. Since 2.16POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED=131— POSIX collating elements are not supported. Since 2.16HEX_CODE_TOO_LARGE=134— Character value in "\x{...}" sequence is too large. Since 2.16INVALID_CONDITION=135— Invalid condition "(?(0)". Since 2.16SINGLE_BYTE_MATCH_IN_LOOKBEHIND=136— \C not allowed in lookbehind assertion. Since 2.16INFINITE_LOOP=140— Recursive call could loop indefinitely. Since 2.16MISSING_SUBPATTERN_NAME_TERMINATOR=142— Missing terminator in subpattern name. Since 2.16DUPLICATE_SUBPATTERN_NAME=143— Two named subpatterns have the same name. Since 2.16MALFORMED_PROPERTY=146— Malformed "\P" or "\p" sequence. Since 2.16UNKNOWN_PROPERTY=147— Unknown property name after "\P" or "\p". Since 2.16SUBPATTERN_NAME_TOO_LONG=148— Subpattern name is too long (maximum 32 characters). Since 2.16TOO_MANY_SUBPATTERNS=149— Too many named subpatterns (maximum 10,000). Since 2.16INVALID_OCTAL_VALUE=151— Octal value is greater than "\377". Since 2.16TOO_MANY_BRANCHES_IN_DEFINE=154— "DEFINE" group contains more than one branch. Since 2.16DEFINE_REPETION=155— Repeating a "DEFINE" group is not allowed. This error is never raised. Since: 2.16 Deprecated: 2.34INCONSISTENT_NEWLINE_OPTIONS=156— Inconsistent newline options. Since 2.16MISSING_BACK_REFERENCE=157— "\g" is not followed by a braced, angle-bracketed, or quoted name or number, or by a plain number. Since: 2.16INVALID_RELATIVE_REFERENCE=158— relative reference must not be zero. Since: 2.34BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN=159— the backtracing control verb used does not allow an argument. Since: 2.34UNKNOWN_BACKTRACKING_CONTROL_VERB=160— unknown backtracing control verb. Since: 2.34NUMBER_TOO_BIG=161— number is too big in escape sequence. Since: 2.34MISSING_SUBPATTERN_NAME=162— Missing subpattern name. Since: 2.34MISSING_DIGIT=163— Missing digit. Since 2.34INVALID_DATA_CHARACTER=164— In JavaScript compatibility mode, "[" is an invalid data character. Since: 2.34EXTRA_SUBPATTERN_NAME=165— different names for subpatterns of the same number are not allowed. Since: 2.34BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED=166— the backtracing control verb requires an argument. Since: 2.34INVALID_CONTROL_CHAR=168— "\c" must be followed by an ASCII character. Since: 2.34MISSING_NAME=169— "\k" is not followed by a braced, angle-bracketed, or quoted name. Since: 2.34NOT_SUPPORTED_IN_CLASS=171— "\N" is not supported in a class. Since: 2.34TOO_MANY_FORWARD_REFERENCES=172— too many forward references. Since: 2.34NAME_TOO_LONG=175— the name is too long in "(MARK)", "(PRUNE)", "(SKIP)", or "(THEN)". Since: 2.34CHARACTER_VALUE_TOO_LARGE=176— the character value in the \u sequence is too large. Since: 2.34
RegexMatchFlags¶
Bit flags.
DEFAULT=0— No special options set. Since: 2.74ANCHORED=16— The pattern is forced to be "anchored", that is, it is constrained to match only at the first matching point in the string that is being searched. This effect can also be achieved by appropriate constructs in the pattern itself such as the "^" metacharacter.NOTBOL=128— Specifies that first character of the string is not the beginning of a line, so the circumflex metacharacter should not match before it. Setting this withoutRegexCompileFlags.MULTILINE(at compile time) causes circumflex never to match. This option affects only the behaviour of the circumflex metacharacter, it does not affect "\A".NOTEOL=256— Specifies that the end of the subject string is not the end of a line, so the dollar metacharacter should not match it nor (except in multiline mode) a newline immediately before it. Setting this withoutRegexCompileFlags.MULTILINE(at compile time) causes dollar never to match. This option affects only the behaviour of the dollar metacharacter, it does not affect "\Z" or "\z".NOTEMPTY=1024— An empty string is not considered to be a valid match if this option is set. If there are alternatives in the pattern, they are tried. If all the alternatives match the empty string, the entire match fails. For example, if the pattern "a?b?" is applied to a string not beginning with "a" or "b", it matches the empty string at the start of the string. With this flag set, this match is not valid, so GRegex searches further into the string for occurrences of "a" or "b".PARTIAL=32768— Turns on the partial matching feature, for more documentation on partial matching seeMatchInfo.is_partial_match.NEWLINE_CR=1048576— Overrides the newline definition set when creating a newRegex, setting the '\r' character as line terminator.NEWLINE_LF=2097152— Overrides the newline definition set when creating a newRegex, setting the '\n' character as line terminator.NEWLINE_CRLF=3145728— Overrides the newline definition set when creating a newRegex, setting the '\r\n' characters sequence as line terminator.NEWLINE_ANY=4194304— Overrides the newline definition set when creating a newRegex, any Unicode newline sequence is recognised as a newline. These are '\r', '\n' and '\rn', and the single characters U+000B LINE TABULATION, U+000C FORM FEED (FF), U+0085 NEXT LINE (NEL), U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR.NEWLINE_ANYCRLF=5242880— Overrides the newline definition set when creating a newRegex; any '\r', '\n', or '\r\n' character sequence is recognized as a newline. Since: 2.34BSR_ANYCRLF=8388608— Overrides the newline definition for "\R" set when creating a newRegex; only '\r', '\n', or '\r\n' character sequences are recognized as a newline by "\R". Since: 2.34BSR_ANY=16777216— Overrides the newline definition for "\R" set when creating a newRegex; any Unicode newline character or character sequence are recognized as a newline by "\R". These are '\r', '\n' and '\rn', and the single characters U+000B LINE TABULATION, U+000C FORM FEED (FF), U+0085 NEXT LINE (NEL), U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR. Since: 2.34PARTIAL_SOFT=32768— An alias forRegexMatchFlags.PARTIAL. Since: 2.34PARTIAL_HARD=134217728— Turns on the partial matching feature. In contrast to toRegexMatchFlags.PARTIAL_SOFT, this stops matching as soon as a partial match is found, without continuing to search for a possible complete match. SeeMatchInfo.is_partial_matchfor more information. Since: 2.34NOTEMPTY_ATSTART=268435456— LikeRegexMatchFlags.NOTEMPTY, but only applied to the start of the matched string. For anchored patterns this can only happen for pattern containing "\K". Since: 2.34
SeekType¶
Enumeration.
CUR=0— the current position in the file.SET=1— the start of the file.END=2— the end of the file.
ShellError¶
Enumeration.
BAD_QUOTING=0— Mismatched or otherwise mangled quoting.EMPTY_STRING=1— String to be parsed was empty.FAILED=2— Some other error.
SliceConfig¶
Enumeration.
ALWAYS_MALLOC=1BYPASS_MAGAZINES=2WORKING_SET_MSECS=3COLOR_INCREMENT=4CHUNK_SIZES=5CONTENTION_COUNTER=6
SpawnError¶
Enumeration.
FORK=0— Fork failed due to lack of memory.READ=1— Read or select on pipes failed.CHDIR=2— Changing to working directory failed.ACCES=3— execv() returnedEACCESPERM=4— execv() returnedEPERMTOO_BIG=5— execv() returnedE2BIG_2BIG=5— deprecated alias forSpawnError.TOO_BIG(deprecated since GLib 2.32)NOEXEC=6— execv() returnedENOEXECNAMETOOLONG=7— execv() returnedENAMETOOLONGNOENT=8— execv() returnedENOENTNOMEM=9— execv() returnedENOMEMNOTDIR=10— execv() returnedENOTDIRLOOP=11— execv() returnedELOOPTXTBUSY=12— execv() returnedETXTBUSYIO=13— execv() returnedEIONFILE=14— execv() returnedENFILEMFILE=15— execv() returnedEMFILEINVAL=16— execv() returnedEINVALISDIR=17— execv() returnedEISDIRLIBBAD=18— execv() returnedELIBBADFAILED=19— Some other fatal failure,error->messageshould explain.
SpawnFlags¶
Bit flags.
DEFAULT=0— no flags, default behaviourLEAVE_DESCRIPTORS_OPEN=1— the parent's open file descriptors will be inherited by the child; otherwise all descriptors except stdin, stdout and stderr will be closed before calling exec() in the child.DO_NOT_REAP_CHILD=2— the child will not be automatically reaped; you must use g_child_watch_add() yourself (or call waitpid() or handleSIGCHLDyourself), or the child will become a zombie.SEARCH_PATH=4—argv[0]need not be an absolute path, it will be looked for in the user'sPATH.STDOUT_TO_DEV_NULL=8— the child's standard output will be discarded, instead of going to the same location as the parent's standard output.STDERR_TO_DEV_NULL=16— the child's standard error will be discarded.CHILD_INHERITS_STDIN=32— the child will inherit the parent's standard input (by default, the child's standard input is attached to/dev/null).FILE_AND_ARGV_ZERO=64— the first element ofargvis the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normallyspawn_async_with_pipesusesargv[0]as the file to execute, and passes all ofargvto the child.SEARCH_PATH_FROM_ENVP=128— ifargv[0]is not an absolute path, it will be looked for in thePATHfrom the passed child environment. Since: 2.34CLOEXEC_PIPES=256— create all pipes with theO_CLOEXECflag set. Since: 2.40CHILD_INHERITS_STDOUT=512— The child will inherit the parent's standard output.CHILD_INHERITS_STDERR=1024— The child will inherit the parent's standard error.STDIN_FROM_DEV_NULL=2048— The child's standard input is attached to/dev/null.
TestFileType¶
Enumeration.
DIST=0— a file that was included in the distribution tarballBUILT=1— a file that was built on the compiling machine
TestLogType¶
Enumeration.
NONE=0ERROR=1START_BINARY=2LIST_CASE=3SKIP_CASE=4START_CASE=5STOP_CASE=6MIN_RESULT=7MAX_RESULT=8MESSAGE=9START_SUITE=10STOP_SUITE=11
TestResult¶
Enumeration.
SUCCESS=0SKIPPED=1FAILURE=2INCOMPLETE=3
TestSubprocessFlags¶
Bit flags.
DEFAULT=0— Default behaviour. Since: 2.74INHERIT_STDIN=1— If this flag is given, the child process will inherit the parent's stdin. Otherwise, the child's stdin is redirected to/dev/null.INHERIT_STDOUT=2— If this flag is given, the child process will inherit the parent's stdout. Otherwise, the child's stdout will not be visible, but it will be captured to allow later tests withGLib.test_trap_assert_stdout.INHERIT_STDERR=4— If this flag is given, the child process will inherit the parent's stderr. Otherwise, the child's stderr will not be visible, but it will be captured to allow later tests withGLib.test_trap_assert_stderr.INHERIT_DESCRIPTORS=8— If this flag is given, the child process will inherit the parent’s open file descriptors.
TestTrapFlags¶
Bit flags.
DEFAULT=0— Default behaviour. Since: 2.74SILENCE_STDOUT=128— Redirect stdout of the test child to/dev/nullso it cannot be observed on the console during test runs. The actual output is still captured though to allow later tests with g_test_trap_assert_stdout().SILENCE_STDERR=256— Redirect stderr of the test child to/dev/nullso it cannot be observed on the console during test runs. The actual output is still captured though to allow later tests with g_test_trap_assert_stderr().INHERIT_STDIN=512— If this flag is given, stdin of the child process is shared with stdin of its parent process. It is redirected to/dev/nullotherwise.
ThreadError¶
Enumeration.
THREAD_ERROR_AGAIN=0— a thread couldn't be created due to resource shortage. Try again later.
TimeType¶
Enumeration.
STANDARD=0— the time is in local standard timeDAYLIGHT=1— the time is in local daylight timeUNIVERSAL=2— the time is in UTC
TokenType¶
Enumeration.
EOF=0— the end of the fileLEFT_PAREN=40— a '(' characterRIGHT_PAREN=41— a ')' characterLEFT_CURLY=123— a '{' characterRIGHT_CURLY=125— a '}' characterLEFT_BRACE=91— a '[' characterRIGHT_BRACE=93— a ']' characterEQUAL_SIGN=61— a '=' characterCOMMA=44— a ',' characterNONE=256— not a tokenERROR=257— an error occurredCHAR=258— a characterBINARY=259— a binary integerOCTAL=260— an octal integerINT=261— an integerHEX=262— a hex integerFLOAT=263— a floating point numberSTRING=264— a stringSYMBOL=265— a symbolIDENTIFIER=266— an identifierIDENTIFIER_NULL=267— a null identifierCOMMENT_SINGLE=268— one line commentCOMMENT_MULTI=269— multi line comment
TraverseFlags¶
Bit flags.
LEAVES=1— only leaf nodes should be visited. This name has been introduced in 2.6, for older version useTraverseFlags.LEAFS.NON_LEAVES=2— only non-leaf nodes should be visited. This name has been introduced in 2.6, for older version useTraverseFlags.NON_LEAFS.ALL=3— all nodes should be visited.MASK=3— a mask of all traverse flags.LEAFS=1— identical toTraverseFlags.LEAVES.NON_LEAFS=2— identical toTraverseFlags.NON_LEAVES.
TraverseType¶
Enumeration.
IN_ORDER=0— visits a node's left child first, then the node itself, then its right child. This is the one to use if you want the output sorted according to the compare function.PRE_ORDER=1— visits a node, then its children.POST_ORDER=2— visits the node's children, then the node itself.LEVEL_ORDER=3— is not implemented for balanced binary trees. For n-ary trees, it visits the root node first, then its children, then its grandchildren, and so on. Note that this is less efficient than the other orders.
UnicodeBreakType¶
Enumeration.
MANDATORY=0— Mandatory Break (BK)CARRIAGE_RETURN=1— Carriage Return (CR)LINE_FEED=2— Line Feed (LF)COMBINING_MARK=3— Attached Characters and Combining Marks (CM)SURROGATE=4— Surrogates (SG)ZERO_WIDTH_SPACE=5— Zero Width Space (ZW)INSEPARABLE=6— Inseparable (IN)NON_BREAKING_GLUE=7— Non-breaking ("Glue") (GL)CONTINGENT=8— Contingent Break Opportunity (CB)SPACE=9— Space (SP)AFTER=10— Break Opportunity After (BA)BEFORE=11— Break Opportunity Before (BB)BEFORE_AND_AFTER=12— Break Opportunity Before and After (B2)HYPHEN=13— Hyphen (HY)NON_STARTER=14— Nonstarter (NS)OPEN_PUNCTUATION=15— Opening Punctuation (OP)CLOSE_PUNCTUATION=16— Closing Punctuation (CL)QUOTATION=17— Ambiguous Quotation (QU)EXCLAMATION=18— Exclamation/Interrogation (EX)IDEOGRAPHIC=19— Ideographic (ID)NUMERIC=20— Numeric (NU)INFIX_SEPARATOR=21— Infix Separator (Numeric) (IS)SYMBOL=22— Symbols Allowing Break After (SY)ALPHABETIC=23— Ordinary Alphabetic and Symbol Characters (AL)PREFIX=24— Prefix (Numeric) (PR)POSTFIX=25— Postfix (Numeric) (PO)COMPLEX_CONTEXT=26— Complex Content Dependent (South East Asian) (SA)AMBIGUOUS=27— Ambiguous (Alphabetic or Ideographic) (AI)UNKNOWN=28— Unknown (XX)NEXT_LINE=29— Next Line (NL)WORD_JOINER=30— Word Joiner (WJ)HANGUL_L_JAMO=31— Hangul L Jamo (JL)HANGUL_V_JAMO=32— Hangul V Jamo (JV)HANGUL_T_JAMO=33— Hangul T Jamo (JT)HANGUL_LV_SYLLABLE=34— Hangul LV Syllable (H2)HANGUL_LVT_SYLLABLE=35— Hangul LVT Syllable (H3)CLOSE_PARANTHESIS=36— Closing Parenthesis (CP). Since 2.28. Deprecated: 2.70: UseUnicodeBreakType.CLOSE_PARENTHESISinstead.CLOSE_PARENTHESIS=36— Closing Parenthesis (CP). Since 2.70CONDITIONAL_JAPANESE_STARTER=37— Conditional Japanese Starter (CJ). Since: 2.32HEBREW_LETTER=38— Hebrew Letter (HL). Since: 2.32REGIONAL_INDICATOR=39— Regional Indicator (RI). Since: 2.36EMOJI_BASE=40— Emoji Base (EB). Since: 2.50EMOJI_MODIFIER=41— Emoji Modifier (EM). Since: 2.50ZERO_WIDTH_JOINER=42— Zero Width Joiner (ZWJ). Since: 2.50AKSARA=43— Aksara (AK). Since: 2.80AKSARA_PRE_BASE=44— Aksara Pre-Base (AP). Since: 2.80AKSARA_START=45— Aksara Start (AS). Since: 2.80VIRAMA_FINAL=46— Virama Final (VF). Since: 2.80VIRAMA=47— Virama (VI). Since: 2.80UNAMBIGUOUS_HYPHEN=48— Unambiguous Hyphen (HH). Since: 2.88
UnicodeScript¶
Enumeration.
INVALID_CODE=-1— a value never returned fromunichar_get_scriptCOMMON=0— a character used by multiple different scriptsINHERITED=1— a mark glyph that takes its script from the base glyph to which it is attachedARABIC=2— ArabicARMENIAN=3— ArmenianBENGALI=4— BengaliBOPOMOFO=5— BopomofoCHEROKEE=6— CherokeeCOPTIC=7— CopticCYRILLIC=8— CyrillicDESERET=9— DeseretDEVANAGARI=10— DevanagariETHIOPIC=11— EthiopicGEORGIAN=12— GeorgianGOTHIC=13— GothicGREEK=14— GreekGUJARATI=15— GujaratiGURMUKHI=16— GurmukhiHAN=17— HanHANGUL=18— HangulHEBREW=19— HebrewHIRAGANA=20— HiraganaKANNADA=21— KannadaKATAKANA=22— KatakanaKHMER=23— KhmerLAO=24— LaoLATIN=25— LatinMALAYALAM=26— MalayalamMONGOLIAN=27— MongolianMYANMAR=28— MyanmarOGHAM=29— OghamOLD_ITALIC=30— Old ItalicORIYA=31— OriyaRUNIC=32— RunicSINHALA=33— SinhalaSYRIAC=34— SyriacTAMIL=35— TamilTELUGU=36— TeluguTHAANA=37— ThaanaTHAI=38— ThaiTIBETAN=39— TibetanCANADIAN_ABORIGINAL=40— Canadian AboriginalYI=41— YiTAGALOG=42— TagalogHANUNOO=43— HanunooBUHID=44— BuhidTAGBANWA=45— TagbanwaBRAILLE=46— BrailleCYPRIOT=47— CypriotLIMBU=48— LimbuOSMANYA=49— OsmanyaSHAVIAN=50— ShavianLINEAR_B=51— Linear BTAI_LE=52— Tai LeUGARITIC=53— UgariticNEW_TAI_LUE=54— New Tai LueBUGINESE=55— BugineseGLAGOLITIC=56— GlagoliticTIFINAGH=57— TifinaghSYLOTI_NAGRI=58— Syloti NagriOLD_PERSIAN=59— Old PersianKHAROSHTHI=60— KharoshthiUNKNOWN=61— an unassigned code pointBALINESE=62— BalineseCUNEIFORM=63— CuneiformPHOENICIAN=64— PhoenicianPHAGS_PA=65— Phags-paNKO=66— N'KoKAYAH_LI=67— Kayah Li. Since 2.16.3LEPCHA=68— Lepcha. Since 2.16.3REJANG=69— Rejang. Since 2.16.3SUNDANESE=70— Sundanese. Since 2.16.3SAURASHTRA=71— Saurashtra. Since 2.16.3CHAM=72— Cham. Since 2.16.3OL_CHIKI=73— Ol Chiki. Since 2.16.3VAI=74— Vai. Since 2.16.3CARIAN=75— Carian. Since 2.16.3LYCIAN=76— Lycian. Since 2.16.3LYDIAN=77— Lydian. Since 2.16.3AVESTAN=78— Avestan. Since 2.26BAMUM=79— Bamum. Since 2.26EGYPTIAN_HIEROGLYPHS=80— Egyptian Hieroglpyhs. Since 2.26IMPERIAL_ARAMAIC=81— Imperial Aramaic. Since 2.26INSCRIPTIONAL_PAHLAVI=82— Inscriptional Pahlavi. Since 2.26INSCRIPTIONAL_PARTHIAN=83— Inscriptional Parthian. Since 2.26JAVANESE=84— Javanese. Since 2.26KAITHI=85— Kaithi. Since 2.26LISU=86— Lisu. Since 2.26MEETEI_MAYEK=87— Meetei Mayek. Since 2.26OLD_SOUTH_ARABIAN=88— Old South Arabian. Since 2.26OLD_TURKIC=89— Old Turkic. Since 2.28SAMARITAN=90— Samaritan. Since 2.26TAI_THAM=91— Tai Tham. Since 2.26TAI_VIET=92— Tai Viet. Since 2.26BATAK=93— Batak. Since 2.28BRAHMI=94— Brahmi. Since 2.28MANDAIC=95— Mandaic. Since 2.28CHAKMA=96— Chakma. Since: 2.32MEROITIC_CURSIVE=97— Meroitic Cursive. Since: 2.32MEROITIC_HIEROGLYPHS=98— Meroitic Hieroglyphs. Since: 2.32MIAO=99— Miao. Since: 2.32SHARADA=100— Sharada. Since: 2.32SORA_SOMPENG=101— Sora Sompeng. Since: 2.32TAKRI=102— Takri. Since: 2.32BASSA_VAH=103— Bassa. Since: 2.42CAUCASIAN_ALBANIAN=104— Caucasian Albanian. Since: 2.42DUPLOYAN=105— Duployan. Since: 2.42ELBASAN=106— Elbasan. Since: 2.42GRANTHA=107— Grantha. Since: 2.42KHOJKI=108— Kjohki. Since: 2.42KHUDAWADI=109— Khudawadi, Sindhi. Since: 2.42LINEAR_A=110— Linear A. Since: 2.42MAHAJANI=111— Mahajani. Since: 2.42MANICHAEAN=112— Manichaean. Since: 2.42MENDE_KIKAKUI=113— Mende Kikakui. Since: 2.42MODI=114— Modi. Since: 2.42MRO=115— Mro. Since: 2.42NABATAEAN=116— Nabataean. Since: 2.42OLD_NORTH_ARABIAN=117— Old North Arabian. Since: 2.42OLD_PERMIC=118— Old Permic. Since: 2.42PAHAWH_HMONG=119— Pahawh Hmong. Since: 2.42PALMYRENE=120— Palmyrene. Since: 2.42PAU_CIN_HAU=121— Pau Cin Hau. Since: 2.42PSALTER_PAHLAVI=122— Psalter Pahlavi. Since: 2.42SIDDHAM=123— Siddham. Since: 2.42TIRHUTA=124— Tirhuta. Since: 2.42WARANG_CITI=125— Warang Citi. Since: 2.42AHOM=126— Ahom. Since: 2.48ANATOLIAN_HIEROGLYPHS=127— Anatolian Hieroglyphs. Since: 2.48HATRAN=128— Hatran. Since: 2.48MULTANI=129— Multani. Since: 2.48OLD_HUNGARIAN=130— Old Hungarian. Since: 2.48SIGNWRITING=131— Signwriting. Since: 2.48ADLAM=132— Adlam. Since: 2.50BHAIKSUKI=133— Bhaiksuki. Since: 2.50MARCHEN=134— Marchen. Since: 2.50NEWA=135— Newa. Since: 2.50OSAGE=136— Osage. Since: 2.50TANGUT=137— Tangut. Since: 2.50MASARAM_GONDI=138— Masaram Gondi. Since: 2.54NUSHU=139— Nushu. Since: 2.54SOYOMBO=140— Soyombo. Since: 2.54ZANABAZAR_SQUARE=141— Zanabazar Square. Since: 2.54DOGRA=142— Dogra. Since: 2.58GUNJALA_GONDI=143— Gunjala Gondi. Since: 2.58HANIFI_ROHINGYA=144— Hanifi Rohingya. Since: 2.58MAKASAR=145— Makasar. Since: 2.58MEDEFAIDRIN=146— Medefaidrin. Since: 2.58OLD_SOGDIAN=147— Old Sogdian. Since: 2.58SOGDIAN=148— Sogdian. Since: 2.58ELYMAIC=149— Elym. Since: 2.62NANDINAGARI=150— Nand. Since: 2.62NYIAKENG_PUACHUE_HMONG=151— Rohg. Since: 2.62WANCHO=152— Wcho. Since: 2.62CHORASMIAN=153— Chorasmian. Since: 2.66DIVES_AKURU=154— Dives Akuru. Since: 2.66KHITAN_SMALL_SCRIPT=155— Khitan small script. Since: 2.66YEZIDI=156— Yezidi. Since: 2.66CYPRO_MINOAN=157— Cypro-Minoan. Since: 2.72OLD_UYGHUR=158— Old Uyghur. Since: 2.72TANGSA=159— Tangsa. Since: 2.72TOTO=160— Toto. Since: 2.72VITHKUQI=161— Vithkuqi. Since: 2.72MATH=162— Mathematical notation. Since: 2.72KAWI=163— Kawi. Since 2.74NAG_MUNDARI=164— Nag Mundari. Since 2.74TODHRI=165— Todhri. Since: 2.84GARAY=166— Garay. Since: 2.84TULU_TIGALARI=167— Tulu-Tigalari. Since: 2.84SUNUWAR=168— Sunuwar. Since: 2.84GURUNG_KHEMA=169— Gurung Khema. Since: 2.84KIRAT_RAI=170— Kirat Rai. Since: 2.84OL_ONAL=171— Ol Onal. Since: 2.84SIDETIC=172— Sidetic. Since: 2.88TOLONG_SIKI=173— Tolong Siki. Since: 2.88TAI_YO=174— Tai Yo. Since: 2.88BERIA_ERFE=175— Beria Erfe. Since: 2.88
UnicodeType¶
Enumeration.
CONTROL=0— General category "Other, Control" (Cc)FORMAT=1— General category "Other, Format" (Cf)UNASSIGNED=2— General category "Other, Not Assigned" (Cn)PRIVATE_USE=3— General category "Other, Private Use" (Co)SURROGATE=4— General category "Other, Surrogate" (Cs)LOWERCASE_LETTER=5— General category "Letter, Lowercase" (Ll)MODIFIER_LETTER=6— General category "Letter, Modifier" (Lm)OTHER_LETTER=7— General category "Letter, Other" (Lo)TITLECASE_LETTER=8— General category "Letter, Titlecase" (Lt)UPPERCASE_LETTER=9— General category "Letter, Uppercase" (Lu)SPACING_MARK=10— General category "Mark, Spacing" (Mc)ENCLOSING_MARK=11— General category "Mark, Enclosing" (Me)NON_SPACING_MARK=12— General category "Mark, Nonspacing" (Mn)DECIMAL_NUMBER=13— General category "Number, Decimal Digit" (Nd)LETTER_NUMBER=14— General category "Number, Letter" (Nl)OTHER_NUMBER=15— General category "Number, Other" (No)CONNECT_PUNCTUATION=16— General category "Punctuation, Connector" (Pc)DASH_PUNCTUATION=17— General category "Punctuation, Dash" (Pd)CLOSE_PUNCTUATION=18— General category "Punctuation, Close" (Pe)FINAL_PUNCTUATION=19— General category "Punctuation, Final quote" (Pf)INITIAL_PUNCTUATION=20— General category "Punctuation, Initial quote" (Pi)OTHER_PUNCTUATION=21— General category "Punctuation, Other" (Po)OPEN_PUNCTUATION=22— General category "Punctuation, Open" (Ps)CURRENCY_SYMBOL=23— General category "Symbol, Currency" (Sc)MODIFIER_SYMBOL=24— General category "Symbol, Modifier" (Sk)MATH_SYMBOL=25— General category "Symbol, Math" (Sm)OTHER_SYMBOL=26— General category "Symbol, Other" (So)LINE_SEPARATOR=27— General category "Separator, Line" (Zl)PARAGRAPH_SEPARATOR=28— General category "Separator, Paragraph" (Zp)SPACE_SEPARATOR=29— General category "Separator, Space" (Zs)
UriError¶
Enumeration.
FAILED=0— Generic error if no more specific error is available. See the error message for details.BAD_SCHEME=1— The scheme of a URI could not be parsed.BAD_USER=2— The user/userinfo of a URI could not be parsed.BAD_PASSWORD=3— The password of a URI could not be parsed.BAD_AUTH_PARAMS=4— The authentication parameters of a URI could not be parsed.BAD_HOST=5— The host of a URI could not be parsed.BAD_PORT=6— The port of a URI could not be parsed.BAD_PATH=7— The path of a URI could not be parsed.BAD_QUERY=8— The query of a URI could not be parsed.BAD_FRAGMENT=9— The fragment of a URI could not be parsed.
UriFlags¶
Bit flags.
NONE=0— No flags set.PARSE_RELAXED=1— Parse the URI more relaxedly than the RFC 3986 grammar specifies, fixing up or ignoring common mistakes in URIs coming from external sources. This is also needed for some obscure URI schemes where;separates the host from the path. Don’t use this flag unless you need to.HAS_PASSWORD=2— The userinfo field may contain a password, which will be separated from the username by:.HAS_AUTH_PARAMS=4— The userinfo may contain additional authentication-related parameters, which will be separated from the username and/or password by;.ENCODED=8— When parsing a URI, this indicates that%-encoded characters in the userinfo, path, query, and fragment fields should not be decoded. (And likewise the host field ifUriFlags.NON_DNSis also set.) When building a URI, it indicates that you have already%-encoded the components, and soUrishould not do any encoding itself.NON_DNS=16— The host component should not be assumed to be a DNS hostname or IP address (for example, forsmbURIs with NetBIOS hostnames).ENCODED_QUERY=32— Same asUriFlags.ENCODED, for the query field only.ENCODED_PATH=64— Same asUriFlags.ENCODED, for the path only.ENCODED_FRAGMENT=128— Same asUriFlags.ENCODED, for the fragment only.SCHEME_NORMALIZE=256— A scheme-based normalization will be applied. For example, when parsing an HTTP URI changing omitted path to/and omitted port to80; and when building a URI, changing empty path to/and default port80). This only supports a subset of known schemes. (Since: 2.68)
UriHideFlags¶
Bit flags.
NONE=0— No flags set.USERINFO=1— Hide the userinfo.PASSWORD=2— Hide the password.AUTH_PARAMS=4— Hide the auth_params.QUERY=8— Hide the query.FRAGMENT=16— Hide the fragment.
UriParamsFlags¶
Bit flags.
NONE=0— No flags set.CASE_INSENSITIVE=1— Parameter names are case insensitive.WWW_FORM=2— Replace+with space character. Only useful for URLs on the web, using thehttpsorhttpschemas.PARSE_RELAXED=4— SeeUriFlags.PARSE_RELAXED.
UserDirectory¶
Enumeration.
DIRECTORY_DESKTOP=0— the user's Desktop directoryDIRECTORY_DOCUMENTS=1— the user's Documents directoryDIRECTORY_DOWNLOAD=2— the user's Downloads directoryDIRECTORY_MUSIC=3— the user's Music directoryDIRECTORY_PICTURES=4— the user's Pictures directoryDIRECTORY_PUBLIC_SHARE=5— the user's shared directoryDIRECTORY_TEMPLATES=6— the user's Templates directoryDIRECTORY_VIDEOS=7— the user's Movies directoryN_DIRECTORIES=8— the number of enum values
VariantClass¶
Enumeration.
BOOLEAN=98— TheVariantis a boolean.BYTE=121— TheVariantis a byte.INT16=110— TheVariantis a signed 16 bit integer.UINT16=113— TheVariantis an unsigned 16 bit integer.INT32=105— TheVariantis a signed 32 bit integer.UINT32=117— TheVariantis an unsigned 32 bit integer.INT64=120— TheVariantis a signed 64 bit integer.UINT64=116— TheVariantis an unsigned 64 bit integer.HANDLE=104— TheVariantis a file handle index.DOUBLE=100— TheVariantis a double precision floating point value.STRING=115— TheVariantis a normal string.OBJECT_PATH=111— TheVariantis a D-Bus object path string.SIGNATURE=103— TheVariantis a D-Bus signature string.VARIANT=118— TheVariantis a variant.MAYBE=109— TheVariantis a maybe-typed value.ARRAY=97— TheVariantis an array.TUPLE=40— TheVariantis a tuple.DICT_ENTRY=123— TheVariantis a dictionary entry.
VariantParseError¶
Enumeration.
FAILED=0— generic error (unused)BASIC_TYPE_EXPECTED=1— a non-basicVariantTypewas given where a basic type was expectedCANNOT_INFER_TYPE=2— cannot infer theVariantTypeDEFINITE_TYPE_EXPECTED=3— an indefiniteVariantTypewas given where a definite type was expectedINPUT_NOT_AT_END=4— extra data after parsing finishedINVALID_CHARACTER=5— invalid character in number or unicode escapeINVALID_FORMAT_STRING=6— not a validVariantformat stringINVALID_OBJECT_PATH=7— not a valid object pathINVALID_SIGNATURE=8— not a valid type signatureINVALID_TYPE_STRING=9— not a validVarianttype stringNO_COMMON_TYPE=10— could not find a common type for array entriesNUMBER_OUT_OF_RANGE=11— the numerical value is out of range of the given typeNUMBER_TOO_BIG=12— the numerical value is out of range for any typeTYPE_ERROR=13— cannot parse as variant of the specified typeUNEXPECTED_TOKEN=14— an unexpected token was encounteredUNKNOWN_KEYWORD=15— an unknown keyword was encounteredUNTERMINATED_STRING_CONSTANT=16— unterminated string constantVALUE_EXPECTED=17— no value givenRECURSION=18— variant was too deeply nested;Variantis only guaranteed to handle nesting up to 64 levels (Since: 2.64)
Constants¶
ALLOCATOR_LIST¶
ALLOCATOR_NODE¶
ALLOCATOR_SLIST¶
ALLOC_AND_FREE¶
ALLOC_ONLY¶
ANALYZER_ANALYZING¶
ASCII_DTOSTR_BUF_SIZE¶
A good size for a buffer to be passed into ascii_dtostr.
It is guaranteed to be enough for all output of that function
on systems with 64bit IEEE-compatible doubles.
The typical usage would be something like:
char buf[G_ASCII_DTOSTR_BUF_SIZE];
fprintf (out, "value=%s\n", g_ascii_dtostr (buf, sizeof (buf), value));
ATOMIC_REF_COUNT_INIT¶
Evaluates to the initial reference count for gatomicrefcount.
This macro is useful for initializing gatomicrefcount fields inside
structures, for instance:
typedef struct {
gatomicrefcount ref_count;
char *name;
char *address;
} Person;
static const Person default_person = {
.ref_count = G_ATOMIC_REF_COUNT_INIT,
.name = "Default name",
.address = "Default address",
};
BIG_ENDIAN¶
Specifies one of the possible types of byte order.
See G_BYTE_ORDER.
CSET_A_2_Z¶
The set of uppercase ASCII alphabet characters.
Used for specifying valid identifier characters
in ScannerConfig.
CSET_DIGITS¶
The set of ASCII digits.
Used for specifying valid identifier characters
in ScannerConfig.
CSET_a_2_z¶
The set of lowercase ASCII alphabet characters.
Used for specifying valid identifier characters
in ScannerConfig.
C_STD_VERSION¶
The C standard version the code is compiling against, it's normally
defined with the same value of __STDC_VERSION__ for C standard
compatible compilers, while it uses the lowest standard version
in pure MSVC, given that in such compiler the definition depends on
a compilation flag.
This is granted to be undefined when compiling with a C++ compiler.
See also: G_C_STD_CHECK_VERSION and G_CXX_STD_VERSION
DATALIST_FLAGS_MASK¶
A bitmask that restricts the possible flags passed to
datalist_set_flags. Passing a flags value where
flags & ~G_DATALIST_FLAGS_MASK != 0 is an error.
DATE_BAD_DAY¶
Represents an invalid GDateDay.
DATE_BAD_JULIAN¶
Represents an invalid Julian day number.
DATE_BAD_YEAR¶
Represents an invalid year.
DIR_SEPARATOR¶
The directory separator character.
This is '/' on UNIX machines and '\' under Windows.
DIR_SEPARATOR_S¶
The directory separator as a string.
This is "/" on UNIX machines and "\" under Windows.
E¶
The base of natural logarithms.
GINT16_FORMAT¶
GINT16_MODIFIER¶
GINT32_FORMAT¶
GINT32_MODIFIER¶
GINT64_FORMAT¶
GINT64_MODIFIER¶
GINTPTR_FORMAT¶
GINTPTR_MODIFIER¶
GNUC_FUNCTION¶
Expands to "" on all modern compilers, and to FUNCTION on gcc version 2.x. Don't use it.
GNUC_PRETTY_FUNCTION¶
Expands to "" on all modern compilers, and to PRETTY_FUNCTION on gcc version 2.x. Don't use it.
GSIZE_FORMAT¶
GSIZE_MODIFIER¶
GSSIZE_FORMAT¶
GSSIZE_MODIFIER¶
GUINT16_FORMAT¶
GUINT32_FORMAT¶
GUINT64_FORMAT¶
GUINTPTR_FORMAT¶
HAVE_GINT64¶
HAVE_GNUC_VARARGS¶
HAVE_GNUC_VISIBILITY¶
Defined to 1 if gcc-style visibility handling is supported.
HAVE_GROWING_STACK¶
HAVE_ISO_VARARGS¶
HOOK_FLAG_USER_SHIFT¶
The position of the first bit which is not reserved for internal
use be the Hook implementation, i.e.
1 << G_HOOK_FLAG_USER_SHIFT is the first
bit which can be used for application-defined flags.
IEEE754_DOUBLE_BIAS¶
The bias by which exponents in double-precision floats are offset.
IEEE754_FLOAT_BIAS¶
The bias by which exponents in single-precision floats are offset.
KEY_FILE_DESKTOP_GROUP¶
The name of the main group of a desktop entry file, as defined in the Desktop Entry Specification.
Consult the specification for more details about the meanings of the keys below.
KEY_FILE_DESKTOP_KEY_ACTIONS¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a string list
giving the available application actions.
KEY_FILE_DESKTOP_KEY_CATEGORIES¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a list
of strings giving the categories in which the desktop entry
should be shown in a menu.
KEY_FILE_DESKTOP_KEY_COMMENT¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a localized
string giving the tooltip for the desktop entry.
KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean
set to true if the application is D-Bus activatable.
KEY_FILE_DESKTOP_KEY_EXEC¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a string
giving the command line to execute.
It is only valid for desktop entries with the Application type.
KEY_FILE_DESKTOP_KEY_GENERIC_NAME¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a localized
string giving the generic name of the desktop entry.
KEY_FILE_DESKTOP_KEY_HIDDEN¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean
stating whether the desktop entry has been deleted by the user.
KEY_FILE_DESKTOP_KEY_ICON¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a localized
string giving the name of the icon to be displayed for the desktop
entry.
KEY_FILE_DESKTOP_KEY_MIME_TYPE¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a list
of strings giving the MIME types supported by this desktop entry.
KEY_FILE_DESKTOP_KEY_NAME¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a localized
string giving the specific name of the desktop entry.
KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a list of
strings identifying the environments that should not display the
desktop entry.
KEY_FILE_DESKTOP_KEY_NO_DISPLAY¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean
stating whether the desktop entry should be shown in menus.
KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a list of
strings identifying the environments that should display the
desktop entry.
KEY_FILE_DESKTOP_KEY_PATH¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a string
containing the working directory to run the program in.
It is only valid for desktop entries with the Application type.
KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean
stating whether the application supports the
Startup Notification Protocol Specification.
KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is string
identifying the WM class or name hint of a window that the application
will create, which can be used to emulate
Startup Notification
with older applications.
KEY_FILE_DESKTOP_KEY_TERMINAL¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean
stating whether the program should be run in a terminal window.
It is only valid for desktop entries with the Application type.
KEY_FILE_DESKTOP_KEY_TRY_EXEC¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a string
giving the file name of a binary on disk used to determine if the
program is actually installed.
It is only valid for desktop entries with the Application type.
KEY_FILE_DESKTOP_KEY_TYPE¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a string
giving the type of the desktop entry.
Usually KEY_FILE_DESKTOP_TYPE_APPLICATION,
KEY_FILE_DESKTOP_TYPE_LINK, or
KEY_FILE_DESKTOP_TYPE_DIRECTORY.
KEY_FILE_DESKTOP_KEY_URL¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a string
giving the URL to access.
It is only valid for desktop entries with the Link type.
KEY_FILE_DESKTOP_KEY_VERSION¶
A key under KEY_FILE_DESKTOP_GROUP, whose value is a string
giving the version of the Desktop Entry Specification used for
the desktop entry file.
KEY_FILE_DESKTOP_TYPE_APPLICATION¶
The value of the KEY_FILE_DESKTOP_KEY_TYPE, key for desktop
entries representing applications.
KEY_FILE_DESKTOP_TYPE_DIRECTORY¶
The value of the KEY_FILE_DESKTOP_KEY_TYPE, key for desktop
entries representing directories.
KEY_FILE_DESKTOP_TYPE_LINK¶
The value of the KEY_FILE_DESKTOP_KEY_TYPE, key for desktop
entries representing links to documents.
LITTLE_ENDIAN¶
Specifies one of the possible types of byte order.
See G_BYTE_ORDER.
LN10¶
The natural logarithm of 10.
LN2¶
The natural logarithm of 2.
LOG_2_BASE_10¶
Multiplying the base 2 exponent by this number yields the base 10 exponent.
LOG_DOMAIN¶
Defines the log domain. See Log Domains.
Libraries should define this so that any messages which they log can be differentiated from messages from other libraries and application code. But be careful not to define it in any public header files.
Log domains must be unique, and it is recommended that they are the
application or library name, optionally followed by a hyphen and a sub-domain
name. For example, bloatpad or bloatpad-io.
If undefined, it defaults to the default None (or "") log domain; this is
not advisable, as it cannot be filtered against using the G_MESSAGES_DEBUG
environment variable.
For example, GTK uses this in its Makefile.am:
Applications can choose to leave it as the default None (or "")
domain. However, defining the domain offers the same advantages as
above.
LOG_FATAL_MASK¶
GLib log levels that are considered fatal by default.
This is not used if structured logging is enabled; see Using Structured Logging.
LOG_LEVEL_USER_SHIFT¶
Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
Higher bits can be used for user-defined log levels.
MAJOR_VERSION¶
The major version number of the GLib library.
Like #glib_major_version, but from the headers used at application compile time, rather than from the library linked against at application run time.
MAXINT16¶
MAXINT32¶
MAXINT64¶
MAXINT8¶
MAXUINT16¶
MAXUINT32¶
MAXUINT64¶
MAXUINT8¶
MICRO_VERSION¶
The micro version number of the GLib library.
Like #gtk_micro_version, but from the headers used at application compile time, rather than from the library linked against at application run time.
MININT16¶
The minimum value which can be held in a #gint16.
MININT32¶
The minimum value which can be held in a #gint32.
MININT64¶
The minimum value which can be held in a #gint64.
MININT8¶
The minimum value which can be held in a #gint8.
MINOR_VERSION¶
The minor version number of the GLib library.
Like #gtk_minor_version, but from the headers used at application compile time, rather than from the library linked against at application run time.
MODULE_SUFFIX¶
NSEC_PER_SEC¶
Number of nanoseconds in one second (1 billion). This macro is provided for code readability.
OPTION_REMAINING¶
If a long option in the main group has this name, it is not treated as a
regular option. Instead it collects all non-option arguments which would
otherwise be left in argv. The option must be of type
OptionArg.CALLBACK, OptionArg.STRING_ARRAY
or OptionArg.FILENAME_ARRAY.
Using OPTION_REMAINING instead of simply scanning argv
for leftover arguments has the advantage that GOption takes care of
necessary encoding conversions for strings or filenames.
PDP_ENDIAN¶
Specifies one of the possible types of byte order
(currently unused). See G_BYTE_ORDER.
PI¶
The value of pi (ratio of circle's circumference to its diameter).
PID_FORMAT¶
A format specifier that can be used in printf()-style format strings
when printing a GPid.
PI_2¶
Pi divided by 2.
PI_4¶
Pi divided by 4.
POLLFD_FORMAT¶
A format specifier that can be used in printf()-style format strings
when printing the fd member of a PollFD.
PRIORITY_DEFAULT¶
Use this for default priority event sources.
In GLib this priority is used when adding timeout functions
with timeout_add. In GDK this priority is used for events
from the X server.
PRIORITY_DEFAULT_IDLE¶
Use this for default priority idle functions.
In GLib this priority is used when adding idle functions with
idle_add.
PRIORITY_HIGH¶
Use this for high priority event sources.
It is not used within GLib or GTK.
PRIORITY_HIGH_IDLE¶
Use this for high priority idle functions.
GTK uses PRIORITY_HIGH_IDLE + 10 for resizing operations,
and PRIORITY_HIGH_IDLE + 20 for redrawing operations. (This is
done to ensure that any pending resizes are processed before any
pending redraws, so that widgets are not redrawn twice unnecessarily.)
PRIORITY_LOW¶
Use this for very low priority background tasks.
It is not used within GLib or GTK.
REF_COUNT_INIT¶
Evaluates to the initial reference count for grefcount.
This macro is useful for initializing grefcount fields inside
structures, for instance:
typedef struct {
grefcount ref_count;
char *name;
char *address;
} Person;
static const Person default_person = {
.ref_count = G_REF_COUNT_INIT,
.name = "Default name",
.address = "Default address",
};
SEARCHPATH_SEPARATOR¶
The search path separator character. This is ':' on UNIX machines and ';' under Windows.
SEARCHPATH_SEPARATOR_S¶
The search path separator as a string. This is ":" on UNIX machines and ";" under Windows.
SIZEOF_LONG¶
SIZEOF_SIZE_T¶
SIZEOF_SSIZE_T¶
SIZEOF_VOID_P¶
SOURCE_CONTINUE¶
Use this macro as the return value of a SourceFunc to leave
the Source in the main loop.
SOURCE_REMOVE¶
Use this macro as the return value of a SourceFunc to remove
the Source from the main loop.
SQRT2¶
The square root of two.
STR_DELIMITERS¶
The standard delimiters, used in strdelimit.
SYSDEF_AF_INET¶
SYSDEF_AF_INET6¶
SYSDEF_AF_UNIX¶
SYSDEF_MSG_DONTROUTE¶
SYSDEF_MSG_OOB¶
SYSDEF_MSG_PEEK¶
TEST_OPTION_ISOLATE_DIRS¶
A value that can be passed as an option to GLib.test_init.
Creates a unique temporary directory for each unit test and uses sets XDG directories to point into subdirectories of it for the duration of the unit test. The directory tree is cleaned up after the test finishes successfully.
Note that this doesn’t take effect until test_run is called,
so calls to (for example) get_home_dir will return the
system-wide value when made in a test program’s main() function.
The following functions will return subdirectories of the temporary directory when this option is used. The specific subdirectory paths in use are not guaranteed to be stable API — always use a getter function to retrieve them.
get_home_dirget_user_cache_dirget_system_config_dirsget_user_config_dirget_system_data_dirsget_user_data_dirget_user_state_dirget_user_runtime_dir
The subdirectories may not be created by the test harness; as with normal
calls to functions like get_user_cache_dir, the caller must
be prepared to create the directory if it doesn’t exist.
TEST_OPTION_NONFATAL_ASSERTIONS¶
A value that can be passed as an option to GLib.test_init.
If this option is given, assertions will not abort the process, but
call test_fail. Equivalent to test_set_nonfatal_assertions.
TEST_OPTION_NO_PRGNAME¶
A value that can be passed as an option to GLib.test_init.
If this option is given, GLib.test_init will not call set_prgname.
TIME_SPAN_DAY¶
Evaluates to a time span of one day.
TIME_SPAN_HOUR¶
Evaluates to a time span of one hour.
TIME_SPAN_MILLISECOND¶
Evaluates to a time span of one millisecond.
TIME_SPAN_MINUTE¶
Evaluates to a time span of one minute.
TIME_SPAN_SECOND¶
Evaluates to a time span of one second.
UNICHAR_MAX_DECOMPOSITION_LENGTH¶
The maximum length (in codepoints) of a compatibility or canonical decomposition of a single Unicode character.
This is as defined by Unicode 6.1.
URI_RESERVED_CHARS_GENERIC_DELIMITERS¶
Generic delimiters characters as defined in
RFC 3986. Includes :/?#[]@.
URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS¶
Subcomponent delimiter characters as defined in
RFC 3986. Includes !$&'()*+,;=.
USEC_PER_SEC¶
Number of microseconds in one second (1 million). This macro is provided for code readability.
VA_COPY_AS_ARRAY¶
VERSION_MIN_REQUIRED¶
A macro that should be defined by the user prior to including
the glib.h header.
The definition should be one of the predefined GLib version
macros: GLIB_VERSION_2_26, GLIB_VERSION_2_28,...
This macro defines the earliest version of GLib that the package is required to be able to compile against.
If the compiler is configured to warn about the use of deprecated
functions, then using functions that were deprecated in version
VERSION_MIN_REQUIRED or earlier will cause warnings (but
using functions deprecated in later releases will not).
WIN32_MSG_HANDLE¶
macro__has_attributenoreturn_ {#constant-macrohas_attribute___noreturn__}¶
macro__has_attribute_ifunc¶
macro__has_attribute_no_sanitize_address¶
Callbacks¶
CacheDestroyFunc¶
CacheDupFunc¶
CacheNewFunc¶
ChildWatchFunc¶
ClearHandleFunc¶
CompareDataFunc¶
CompareFunc¶
CompletionFunc¶
CompletionStrncmpFunc¶
CopyFunc¶
DataForeachFunc¶
DestroyNotify¶
DuplicateFunc¶
EqualFunc¶
EqualFuncFull¶
ErrorClearFunc¶
ErrorCopyFunc¶
ErrorInitFunc¶
FDSourceFunc¶
FreeFunc¶
Func¶
HFunc¶
HRFunc¶
HashFunc¶
HookCheckFunc¶
HookCheckMarshaller¶
HookCompareFunc¶
HookFinalizeFunc¶
HookFindFunc¶
HookFunc¶
HookMarshaller¶
IOFunc¶
LogFunc¶
LogWriterFunc¶
LogWriterFunc = Callable[[log_level: LogLevelFlags | int, fields: list[LogField]], LogWriterOutput | int]