Functions#
- access(filename: str, mode: int) int#
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().
Added in version 2.8.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
mode – as in access()
- Returns:
zero if the pathname refers to an existing file system object that has all the tested permissions, or -1 otherwise or on error.
- aligned_alloc(n_blocks: int, n_block_bytes: int, alignment: int) Any | None#
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()oraligned_free().Added in version 2.72.
- Parameters:
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
alignment – the alignment to be enforced, which must be a positive power of 2 and a multiple of
sizeof(void*)
- Returns:
the allocated memory
- aligned_alloc0(n_blocks: int, n_block_bytes: int, alignment: int) Any | None#
This function is similar to
aligned_alloc(), but it will also clear the allocated memory before returning it.Added in version 2.72.
- Parameters:
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
alignment – the alignment to be enforced, which must be a positive power of 2 and a multiple of
sizeof(void*)
- Returns:
the allocated, cleared memory
- aligned_free(mem: Any = None) None#
Frees the memory allocated by
aligned_alloc().Added in version 2.72.
- Parameters:
mem – the memory to deallocate
- aligned_free_sized(mem: Any, alignment: int, size: int) None#
Frees the memory pointed to by
mem, assuming it is has the givensizeandalignment.If
memisNonethis is a no-op (andsizeis ignored).It is an error if
sizedoesn’t match the size, oralignmentdoesn’t match the alignment, passed whenmemwas allocated.sizeandalignmentare passed to this function to allow optimizations in the allocator. If you don’t know either of them, usealigned_free()instead.Added in version 2.76.
- Parameters:
mem – the memory to free
alignment – alignment of
memsize – size of
mem, in bytes
- ascii_digit_value(c: int) int#
Determines the numeric value of a character as a decimal digit. If the character is not a decimal digit according to
ascii_isdigit,-1is returned.Differs from
unichar_digit_valuebecause it takes a char, so there’s no worry about sign extension if characters are signed.- Parameters:
c – an ASCII character
- Returns:
the numerical value of
cif it is a decimal digit,-1otherwise
- ascii_dtostr(buffer: str, buf_len: int, d: float) str#
Converts a
gdoubleto a string, using the ‘.’ as decimal point.This function generates enough precision that converting the string back using
ascii_strtodgives 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 thanASCII_DTOSTR_BUF_SIZEbytes, including the terminating nul character, which is always added.- Parameters:
buffer – a buffer to place the resulting string in
buf_len – the length of the buffer
d – the value to convert
- Returns:
the pointer to the buffer with the converted string
- ascii_formatd(buffer: str, buf_len: int, format: str, d: float) str#
Converts a
gdoubleto a string, using the ‘.’ as decimal point. To format the number you pass in aprintf()-style format string. Allowed conversion specifiers are ‘e’, ‘E’, ‘f’, ‘F’, ‘g’ and ‘G’.The
formatmust just be a single format specifier starting with%, expecting agdoubleargument.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 in
buf_len – the length of the buffer
format – the
printf()-style format to use for the code to use for convertingd – the value to convert
- Returns:
the pointer to the buffer with the converted string
- ascii_strcasecmp(s1: str, s2: str) int#
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
s1ands2must be non-NULL.- Parameters:
s1 – string to compare with
s2s2 – string to compare with
s1
- Returns:
0 if the strings match, a negative value if
s1<s2, or a positive value ifs1>s2
- ascii_strdown(str: str, len: int) str#
Converts all upper case ASCII letters to lower case ASCII letters, with semantics that exactly match
ascii_tolower.- Parameters:
str – a string
len – length of
strin bytes, or-1ifstris nul-terminated
- Returns:
a newly-allocated string, with all the upper case characters in
strconverted to lower case. (Note that this is unlike the oldstrdown, which modified the string in place.)
- ascii_string_to_signed(str: str, base: int, min: int, max: int) tuple[bool, int]#
A convenience function for converting a string to a signed number.
This function assumes that
strcontains only a number of the givenbasethat is within inclusive bounds limited byminandmax. If this is true, then the converted number is stored inout_num. An empty string is not a valid input. A string with leading or trailing whitespace is also an invalid input.basecan 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_ERRORdomain. If the input is invalid, the error code will beINVALID. If the parsed number is out of bounds -OUT_OF_BOUNDS.See
ascii_strtollif you have more complex needs such as parsing a string which starts with a number, but then has other characters.Added in version 2.54.
- Parameters:
str – a string to convert
base – base of a parsed number
min – a lower bound (inclusive)
max – an upper bound (inclusive)
- Returns:
true if
strwas a number, false otherwise
- ascii_string_to_unsigned(str: str, base: int, min: int, max: int) tuple[bool, int]#
A convenience function for converting a string to an unsigned number.
This function assumes that
strcontains only a number of the givenbasethat is within inclusive bounds limited byminandmax. If this is true, then the converted number is stored inout_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.basecan 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_ERRORdomain. If the input is invalid, the error code will beINVALID. If the parsed number is out of bounds -OUT_OF_BOUNDS.See
ascii_strtoullif you have more complex needs such as parsing a string which starts with a number, but then has other characters.Added in version 2.54.
- Parameters:
str – a string
base – base of a parsed number
min – a lower bound (inclusive)
max – an upper bound (inclusive)
- Returns:
true if
strwas a number, false otherwise
- ascii_strncasecmp(s1: str, s2: str, n: int) int#
Compare
s1ands2, ignoring the case of ASCII characters and any characters after the firstnin each string. If either string is less thannbytes 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_strcasecmpapplies: 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 with
s2s2 – string to compare with
s1n – number of characters to compare
- Returns:
0 if the strings match, a negative value if
s1<s2, or a positive value ifs1>s2
- ascii_strtod(nptr: str) tuple[float, str]#
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_VALis returned (according to the sign of the value), andERANGEis stored inerrno. If the correct value would cause underflow, zero is returned andERANGEis stored inerrno.This function resets
errnobefore callingstrtod()so that you can reliably detect overflow and underflow.- Parameters:
nptr – the string to convert to a numeric value
- Returns:
the converted value
- ascii_strtoll(nptr: str, base: int) tuple[int, str]#
Converts a string to a
gint64value.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,
MAXINT64orMININT64is returned, andERANGEis stored inerrno. If the base is outside the valid range, zero is returned, andEINVALis stored inerrno. If the string conversion fails, zero is returned, andendptrreturnsnptr(ifendptris non-NULL).Added in version 2.12.
- Parameters:
nptr – the string to convert to a numeric value
base – to be used for the conversion, 2..36 or 0
- Returns:
the converted value, or zero on error
- ascii_strtoull(nptr: str, base: int) tuple[int, str]#
Converts a string to a
guint64value.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 aguint64. 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,
MAXUINT64is returned, andERANGEis stored inerrno. If the base is outside the valid range, zero is returned, andEINVALis stored inerrno. If the string conversion fails, zero is returned, andendptrreturnsnptr(ifendptris non-NULL).Added in version 2.2.
- Parameters:
nptr – the string to convert to a numeric value
base – to be used for the conversion, 2..36 or 0
- Returns:
the converted value, or zero on error
- ascii_strup(str: str, len: int) str#
Converts all lower case ASCII letters to upper case ASCII letters, with semantics that exactly match
ascii_toupper.- Parameters:
str – a string
len – length of
strin bytes, or-1ifstris nul-terminated
- Returns:
a newly-allocated string, with all the lower case characters in
strconverted to upper case. (Note that this is unlike the oldstrup, which modified the string in place.)
- ascii_tolower(c: int) int#
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 onEOFbut no need to worry about casting togucharbefore passing a possibly non-ASCII character in.- Parameters:
c – any character
- Returns:
the result of the conversion
- ascii_toupper(c: int) int#
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 onEOFbut no need to worry about casting togucharbefore passing a possibly non-ASCII character in.- Parameters:
c – any character
- Returns:
the result of the conversion
- ascii_xdigit_value(c: int) int#
Determines the numeric value of a character as a hexadecimal digit. If the character is not a hex digit according to
ascii_isxdigit,-1is returned.Differs from
unichar_xdigit_valuebecause it takes a char, so there’s no worry about sign extension if characters are signed.Differs from
unichar_xdigit_valuebecause it takes a char, so there’s no worry about sign extension if characters are signed.- Parameters:
c – an ASCII character
- Returns:
the numerical value of
cif it is a hex digit,-1otherwise
- assert_warning(log_domain: str, file: str, line: int, pretty_function: str, expression: str) None#
- Parameters:
log_domain
file
line
pretty_function
expression
- assertion_message(domain: str, file: str, line: int, func: str, message: str) None#
- Parameters:
domain
file
line
func
message
- assertion_message_cmpint(domain: str, file: str, line: int, func: str, expr: str, arg1: int, cmp: str, arg2: int, numtype: int) None#
- Parameters:
domain
file
line
func
expr
arg1
cmp
arg2
numtype
- assertion_message_cmpstr(domain: str, file: str, line: int, func: str, expr: str, arg1: str, cmp: str, arg2: str) None#
- Parameters:
domain
file
line
func
expr
arg1
cmp
arg2
- assertion_message_cmpstrv(domain: str, file: str, line: int, func: str, expr: str, arg1: str, arg2: str, first_wrong_idx: int) None#
- Parameters:
domain
file
line
func
expr
arg1
arg2
first_wrong_idx
- assertion_message_error(domain: str, file: str, line: int, func: str, expr: str, error: GError, error_domain: int, error_code: int) None#
- Parameters:
domain
file
line
func
expr
error
error_domain
error_code
- async_queue_new() AsyncQueue#
- async_queue_new_full(item_free_func: Callable[[Any], None] | None = None) AsyncQueue#
- Parameters:
item_free_func
- atexit(func: Callable[[], None]) None#
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 callsatexit(), 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 whenatexit()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.Deprecated since version 2.32: It is best to avoid
atexit().- Parameters:
func – the function to call on normal program termination.
- atomic_int_add(atomic: int, val: int) int#
Atomically adds
valto the value ofatomic.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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.4.
- atomic_int_and(atomic: int, val: int) int#
Performs an atomic bitwise ‘and’ of the value of
atomicandval, storing the result back inatomic.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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.30.
- atomic_int_compare_and_exchange(atomic: int, oldval: int, newval: int) bool#
Compares
atomictooldvaland, if equal, sets it tonewval. Ifatomicwas not equal tooldvalthen 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.4.
- atomic_int_compare_and_exchange_full(atomic: int, oldval: int, newval: int) tuple[bool, int]#
Compares
atomictooldvaland, if equal, sets it tonewval. Ifatomicwas not equal tooldvalthen no change occurs. In any case the value ofatomicbefore this operation is stored inpreval.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()Added in version 2.74.
- atomic_int_dec_and_test(atomic: int) bool#
Decrements the value of
atomicby 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.4.
- atomic_int_exchange(atomic: int, newval: int) int#
Sets the
atomictonewvaland returns the old value fromatomic.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.
Added in version 2.74.
- atomic_int_exchange_and_add(atomic: int, val: int) int#
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.Added in version 2.4.
Deprecated since version 2.30: Use
atomic_int_add()instead.- Parameters:
atomic – a pointer to a
intval – the value to add
- Returns:
the value of
atomicbefore the add, signed
- atomic_int_get(atomic: int) int#
Gets the current value of
atomic.This call acts as a full compiler and hardware memory barrier (before the get).
While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.4.
- atomic_int_inc(atomic: int) None#
Increments the value of
atomicby 1.Think of this operation as an atomic version of
{ *atomic += 1; }.This call acts as a full compiler and hardware memory barrier.
While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.4.
- atomic_int_or(atomic: int, val: int) int#
Performs an atomic bitwise ‘or’ of the value of
atomicandval, storing the result back inatomic.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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.30.
- atomic_int_set(atomic: int, newval: int) None#
Sets the value of
atomictonewval.This call acts as a full compiler and hardware memory barrier (after the set).
While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.4.
- atomic_int_xor(atomic: int, val: int) int#
Performs an atomic bitwise ‘xor’ of the value of
atomicandval, storing the result back inatomic.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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.30.
- atomic_pointer_add(atomic: Any, val: int) int#
Atomically adds
valto the value ofatomic.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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.In GLib 2.80, the return type was changed from
gssizetointto add support for platforms with 128-bit pointers. This should not affect existing code.Added in version 2.30.
- Parameters:
atomic – a pointer to a
gpointer-sized valueval – the value to add
- Returns:
the value of
atomicbefore the add, signed
- atomic_pointer_and(atomic: Any, val: int) int#
Performs an atomic bitwise ‘and’ of the value of
atomicandval, storing the result back inatomic.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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.In GLib 2.80, the return type was changed from
gsizetointto add support for platforms with 128-bit pointers. This should not affect existing code.Added in version 2.30.
- Parameters:
atomic – a pointer to a
gpointer-sized valueval – the value to ‘and’
- Returns:
the value of
atomicbefore the operation, unsigned
- atomic_pointer_compare_and_exchange(atomic: Any, oldval: Any = None, newval: Any = None) bool#
Compares
atomictooldvaland, if equal, sets it tonewval. Ifatomicwas not equal tooldvalthen 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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.4.
- Parameters:
atomic – a pointer to a
gpointer-sized valueoldval – the value to compare with
newval – the value to conditionally replace with
- Returns:
Trueif the exchange took place
- atomic_pointer_compare_and_exchange_full(atomic: Any, oldval: Any = None, newval: Any = None) tuple[bool, Any]#
Compares
atomictooldvaland, if equal, sets it tonewval. Ifatomicwas not equal tooldvalthen no change occurs. In any case the value ofatomicbefore this operation is stored inpreval.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()Added in version 2.74.
- Parameters:
atomic – a pointer to a
gpointer-sized valueoldval – the value to compare with
newval – the value to conditionally replace with
- Returns:
Trueif the exchange took place
- atomic_pointer_exchange(atomic: Any = None, newval: Any = None) Any | None#
Sets the
atomictonewvaland returns the old value fromatomic.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.
Added in version 2.74.
- Parameters:
atomic – a pointer to a
gpointer-sized valuenewval – the value to replace with
- Returns:
the value of
atomicbefore the exchange
- atomic_pointer_get(atomic: Any) Any | None#
Gets the current value of
atomic.This call acts as a full compiler and hardware memory barrier (before the get).
While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.4.
- Parameters:
atomic – a pointer to a
gpointer-sized value- Returns:
the value of the pointer
- atomic_pointer_or(atomic: Any, val: int) int#
Performs an atomic bitwise ‘or’ of the value of
atomicandval, storing the result back inatomic.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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.In GLib 2.80, the return type was changed from
gsizetointto add support for platforms with 128-bit pointers. This should not affect existing code.Added in version 2.30.
- Parameters:
atomic – a pointer to a
gpointer-sized valueval – the value to ‘or’
- Returns:
the value of
atomicbefore the operation, unsigned
- atomic_pointer_set(atomic: Any, newval: Any = None) None#
Sets the value of
atomictonewval.This call acts as a full compiler and hardware memory barrier (after the set).
While
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.Added in version 2.4.
- Parameters:
atomic – a pointer to a
gpointer-sized valuenewval – a new value to store
- atomic_pointer_xor(atomic: Any, val: int) int#
Performs an atomic bitwise ‘xor’ of the value of
atomicandval, storing the result back inatomic.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
atomichas avolatilequalifier, this is a historical artifact and the pointer passed to it should not bevolatile.In GLib 2.80, the return type was changed from
gsizetointto add support for platforms with 128-bit pointers. This should not affect existing code.Added in version 2.30.
- Parameters:
atomic – a pointer to a
gpointer-sized valueval – the value to ‘xor’
- Returns:
the value of
atomicbefore the operation, unsigned
- atomic_rc_box_acquire(mem_block: Any) Any#
Atomically acquires a reference on the data pointed by
mem_block.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- Returns:
a pointer to the data, with its reference count increased
- atomic_rc_box_alloc(block_size: int) Any#
Allocates
block_sizebytes 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.
Added in version 2.58.
- Parameters:
block_size – the size of the allocation, must be greater than 0
- Returns:
a pointer to the allocated memory
- atomic_rc_box_alloc0(block_size: int) Any#
Allocates
block_sizebytes 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.
Added in version 2.58.
- Parameters:
block_size – the size of the allocation, must be greater than 0
- Returns:
a pointer to the allocated memory
- atomic_rc_box_dup(block_size: int, mem_block: Any) Any#
Allocates a new block of data with atomic reference counting semantics, and copies
block_sizebytes ofmem_blockinto it.Added in version 2.58.
- Parameters:
block_size – the number of bytes to copy, must be greater than 0
mem_block – the memory to copy
- Returns:
a pointer to the allocated memory
- atomic_rc_box_get_size(mem_block: Any) int#
Retrieves the size of the reference counted data pointed by
mem_block.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- Returns:
the size of the data, in bytes
- atomic_rc_box_release(mem_block: Any) None#
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.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- atomic_rc_box_release_full(mem_block: Any, clear_func: Callable[[Any], None]) None#
Atomically releases a reference on the data pointed by
mem_block.If the reference was the last one, it will call
clear_functo clear the contents ofmem_block, and then will free the resources allocated formem_block.Note that implementing weak references via
clear_funcis not thread-safe: clearing a pointer to the memory from the callback can race with another thread trying to access it asmem_blockalready has a reference count of 0 when the callback is called and will be freed.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
clear_func – a function to call when clearing the data
- base64_decode(text: str) list[int]#
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.
Added in version 2.12.
- Parameters:
text – zero-terminated string with base64 text to decode
- Returns:
newly allocated buffer containing the binary data that
textrepresents. The returned buffer must be freed withfree().
- base64_decode_inplace(text: list[int]) tuple[int, list[int]]#
Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.
Added in version 2.20.
- Parameters:
text – zero-terminated string with base64 text to decode
- Returns:
The binary data that
textresponds. This pointer is the same as the inputtext.
- base64_encode(data: list[int] | None = None) str#
Encode a sequence of binary data into its Base-64 stringified representation.
Added in version 2.12.
- Parameters:
data – the binary data to encode
- Returns:
a newly allocated, zero-terminated Base-64 encoded string representing
data. The returned string must be freed withfree().
- 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
outarray will not be automatically nul-terminated.Added in version 2.12.
- Parameters:
break_lines – whether to break long lines
state – Saved state from
base64_encode_step()save – Saved state from
base64_encode_step()
- Returns:
The number of bytes of output that was written
- 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_linesis 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 withLFcharacters, notCR LFsequences, so the result cannot be passed directly to SMTP or certain other protocols.Added in version 2.12.
- Parameters:
in
break_lines – whether to break long lines
state – Saved state between steps, initialize to 0
save – Saved state between steps, initialize to 0
- Returns:
The number of bytes of output that was written
- basename(file_name: str) str#
Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.
Deprecated since version 2.2: Use
path_get_basename()instead, but notice thatpath_get_basename()allocates new memory for the returned string, unlike this function which returns a pointer into the argument.- Parameters:
file_name – the name of the file
- Returns:
the name of the file without any leading directory components
- bit_lock(address: int, lock_bit: int) None#
Sets the indicated
lock_bitinaddress. If the bit is already set, this call will block untilbit_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). Ifbitis not between 0 and 31 then the result is undefined.This function accesses
addressatomically. All other accesses toaddressmust be atomic in order for this function to work reliably. Whileaddresshas avolatilequalifier, this is a historical artifact and the argument passed to it should not bevolatile.Added in version 2.24.
- Parameters:
address – a pointer to an integer
lock_bit – a bit value between 0 and 31
- bit_nth_lsf(mask: int, nth_bit: int) int#
Find the position of the first bit set in
mask, searching from (but not including)nth_bitupwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, setnth_bitto -1.- Parameters:
mask – a
gulongcontaining flagsnth_bit – the index of the bit to start the search from
- Returns:
the index of the first bit set which is higher than
nth_bit, or -1 if no higher bits are set
- bit_nth_msf(mask: int, nth_bit: int) int#
Find the position of the first bit set in
mask, searching from (but not including)nth_bitdownwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, setnth_bitto -1 or GLIB_SIZEOF_LONG * 8.- Parameters:
mask – a
gulongcontaining flagsnth_bit – the index of the bit to start the search from
- Returns:
the index of the first bit set which is lower than
nth_bit, or -1 if no lower bits are set
- bit_storage(number: int) int#
Gets the number of bits used to hold
number, e.g. ifnumberis 4, 3 bits are needed.- Parameters:
number – a
int- Returns:
the number of bits used to hold
number
- bit_trylock(address: int, lock_bit: int) bool#
Sets the indicated
lock_bitinaddress, returningTrueif successful. If the bit is already set, returnsFalseimmediately.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). Ifbitis not between 0 and 31 then the result is undefined.This function accesses
addressatomically. All other accesses toaddressmust be atomic in order for this function to work reliably. Whileaddresshas avolatilequalifier, this is a historical artifact and the argument passed to it should not bevolatile.Added in version 2.24.
- Parameters:
address – a pointer to an integer
lock_bit – a bit value between 0 and 31
- Returns:
Trueif the lock was acquired
- bit_unlock(address: int, lock_bit: int) None#
Clears the indicated
lock_bitinaddress. If another thread is currently blocked inbit_lock()on this same bit then it will be woken up.This function accesses
addressatomically. All other accesses toaddressmust be atomic in order for this function to work reliably. Whileaddresshas avolatilequalifier, this is a historical artifact and the argument passed to it should not bevolatile.Added in version 2.24.
- Parameters:
address – a pointer to an integer
lock_bit – a bit value between 0 and 31
- build_filenamev(args: list[str]) str#
Creates a filename from a vector of elements using the correct separator for the current platform.
This function behaves exactly like
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
PathBufinstead.Added in version 2.8.
- Parameters:
args –
None-terminated array of strings containing the path elements.- Returns:
the newly allocated path
- build_pathv(separator: str, args: list[str]) str#
Behaves exactly like
build_path(), but takes the path elements as a string array, instead of variadic arguments.This function is mainly meant for language bindings.
Added in version 2.8.
- Parameters:
separator – a string used to separator the elements of the path.
args –
None-terminated array of strings containing the path elements.
- Returns:
a newly-allocated string that must be freed with
free().
- byte_array_remove_range(array: list[int], index_: int, length: int) list[int]#
- Parameters:
array
index
length
- byte_array_sort(array: list[int], compare_func: Callable[[Any, Any], int]) None#
- Parameters:
array
compare_func
- byte_array_sort_with_data(array: list[int], compare_func: Callable[[Any, Any, Any], int], user_data: Any = None) None#
- Parameters:
array
compare_func
user_data
- canonicalize_filename(filename: str, relative_to: str | None = None) str#
Gets the canonical file name from
filename. All triple slashes are turned into single slashes, and all..and.s resolved againstrelative_to.Symlinks are not followed, and the returned path is guaranteed to be absolute.
If
filenameis an absolute path,relative_tois ignored. Otherwise,relative_towill be prepended tofilenameto make it absolute.relative_tomust be an absolute path, orNone. Ifrelative_toisNone, it’ll fallback toget_current_dir().This function never fails, and will canonicalize file paths even if they don’t exist.
No file system I/O is done.
Added in version 2.58.
- Parameters:
filename – the name of the file
relative_to – the relative directory, or
Noneto use the current working directory
- Returns:
a newly allocated string with the canonical file path
- chdir(path: str) int#
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().
Added in version 2.8.
- Parameters:
path – a pathname in the GLib file name encoding (UTF-8 on Windows)
- Returns:
0 on success, -1 if an error occurred.
- check_version(required_major: int, required_minor: int, required_micro: int) str | None#
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_VERSIONas 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.)Added in version 2.6.
- Parameters:
required_major – the required major version
required_minor – the required minor version
required_micro – the required micro version
- Returns:
Noneif the GLib library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by GLib and must not be modified or freed.
- checksum_type_get_length(checksum_type: ChecksumType) int#
- Parameters:
checksum_type
- child_watch_add(*args, **kwargs)#
Sets a function to be called when the child indicated by
pidexits, at a default priority,PRIORITY_DEFAULT.If you obtain
pidfromspawn_asyncorspawn_async_with_pipesyou will need to passDO_NOT_REAP_CHILDas flag to the spawn function for the child watching to work.Note that on platforms where
Pidmust be explicitly closed (seespawn_close_pid)pidmust not be closed while the source is still active. Typically, you will want to callspawn_close_pidin 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_newapply to this function.This internally creates a main loop source using
child_watch_source_newand attaches it to the main loop context usingattach. You can do these steps manually if you need greater control.Added in version 2.4.
- Parameters:
args
kwargs
- Returns:
the ID (greater than 0) of the event source.
- child_watch_source_new(pid: int) Source#
Creates a new child_watch source.
The source will not initially be associated with any
MainContextand must be added to one withattachbefore it will be executed.Note that child watch sources can only be used in conjunction with
g_spawn...when theDO_NOT_REAP_CHILDflag is used.Note that on platforms where
Pidmust be explicitly closed (seespawn_close_pid)pidmust not be closed while the source is still active. Typically, you will want to callspawn_close_pidin 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 processpidmust be positivethe application must not call
waitpidwith a non-positive first argument, for instance in another threadthe application must not wait for
pidto exit by any other mechanism, includingwaitpid(pid, ...)or a second child-watch source for the samepidthe application must not ignore
SIGCHLDBefore 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
ECHILDwas received bywaitpid.Calling
waitpidfor specific processes other thanpidremains a valid thing to do.Added in version 2.4.
- Parameters:
pid – process to watch. On POSIX the positive pid of a child process. On Windows a handle for a process (which doesn’t have to be a child).
- Returns:
the newly-created child watch source
- chmod(filename: str, mode: int) int#
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().
Added in version 2.8.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
mode – as in chmod()
- Returns:
0 if the operation succeeded, -1 on error
- clear_error() None#
If
errorerrisNone, does nothing. Otherwise, callsfree()onerrand setserrtoNone.
- close(fd: int) bool#
This wraps the close() call. In case of error, %errno will be preserved, but the error will also be stored as a
Errorinerror. 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)
errorisNoneandfdis a valid open file descriptor. This makes it safe to call from a signal handler or aSpawnChildSetupFuncunder those conditions. See`signal(7)<man:signal(7)>`__ and`signal-safety(7)<man:signal-safety(7)>`__ for more details.Added in version 2.36.
- Parameters:
fd – A file descriptor
- Returns:
Trueon success,Falseif there was an error.
- closefrom(lowfd: int) int#
Close every file descriptor equal to or greater than
lowfd.Typically
lowfdwill 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 BSDclosefrom (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 [callback``GLib``.SpawnChildSetupFunc], as long as
lowfdis non-negative. See`signal(7)<man:signal(7)>`__ and`signal-safety(7)<man:signal-safety(7)>`__ for more details.Added in version 2.80.
- Parameters:
lowfd – Minimum fd to close, which must be non-negative
- Returns:
0 on success, -1 with errno set on error
- compute_checksum_for_bytes(checksum_type: ChecksumType, data: Bytes) str | None#
Computes the checksum for a binary
data. This is a convenience wrapper fornew(),get_string()andfree().The hexadecimal string returned will be in lower case.
Added in version 2.34.
- Parameters:
checksum_type – a
ChecksumTypedata – binary blob to compute the digest of
- Returns:
the digest of the binary data as a string in hexadecimal, or
Noneifnew()fails forchecksum_type. The returned string should be freed withfree()when done using it.
- compute_checksum_for_data(checksum_type: ChecksumType, data: list[int]) str | None#
Computes the checksum for a binary
dataoflength. This is a convenience wrapper fornew(),get_string()andfree().The hexadecimal string returned will be in lower case.
Added in version 2.16.
- Parameters:
checksum_type – a
ChecksumTypedata – binary blob to compute the digest of
- Returns:
the digest of the binary data as a string in hexadecimal, or
Noneifnew()fails forchecksum_type. The returned string should be freed withfree()when done using it.
- compute_checksum_for_string(checksum_type: ChecksumType, str: str, length: int) str | None#
Computes the checksum of a string.
The hexadecimal string returned will be in lower case.
Added in version 2.16.
- Parameters:
checksum_type – a
ChecksumTypestr – the string to compute the checksum of
length – the length of the string, or -1 if the string is null-terminated.
- Returns:
the checksum as a hexadecimal string, or
Noneifnew()fails forchecksum_type. The returned string should be freed withfree()when done using it.
- compute_hmac_for_bytes(digest_type: ChecksumType, key: Bytes, data: Bytes) str#
Computes the HMAC for a binary
data. This is a convenience wrapper fornew(),get_string()andunref().The hexadecimal string returned will be in lower case.
Added in version 2.50.
- Parameters:
digest_type – a
ChecksumTypeto use for the HMACkey – the key to use in the HMAC
data – binary blob to compute the HMAC of
- Returns:
the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with
free()when done using it.
- compute_hmac_for_data(digest_type: ChecksumType, key: list[int], data: list[int]) str#
Computes the HMAC for a binary
dataoflength. This is a convenience wrapper fornew(),get_string()andunref().The hexadecimal string returned will be in lower case.
Added in version 2.30.
- Parameters:
digest_type – a
ChecksumTypeto use for the HMACkey – the key to use in the HMAC
data – binary blob to compute the HMAC of
- Returns:
the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with
free()when done using it.
- compute_hmac_for_string(digest_type: ChecksumType, key: list[int], str: str, length: int) str#
Computes the HMAC for a string.
The hexadecimal string returned will be in lower case.
Added in version 2.30.
- Parameters:
digest_type – a
ChecksumTypeto use for the HMACkey – the key to use in the HMAC
str – the string to compute the HMAC for
length – the length of the string, or -1 if the string is nul-terminated
- Returns:
the HMAC as a hexadecimal string. The returned string should be freed with
free()when done using it.
- convert(str: list[int], to_codeset: str, from_codeset: str) tuple[list[int], int]#
Converts a string from one character set to another.
Note that you should use
()for streaming conversions. Despite the fact thatbytes_readcan return information about partial characters, theg_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won’t be preserved across successive calls toconvert(),convert_with_iconv()orconvert_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 convert
strfrom_codeset – character set of
str.
- Returns:
If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with
free(). OtherwiseNoneanderrorwill be set.
- 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
fallbackwill be honored. Some systems may do an approximate conversion fromfrom_codesettoto_codesetin their iconv() functions, in which case GLib will simply return that approximate conversion.Note that you should use
()for streaming conversions. Despite the fact thatbytes_readcan return information about partial characters, theg_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won’t be preserved across successive calls toconvert(),convert_with_iconv()orconvert_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 convert
strfrom_codeset – character set of
str.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). If
None, characters not in the target encoding will be represented as Unicode escapes uxxxx or Uxxxxyyyy.
- Returns:
If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with
free(). OtherwiseNoneanderrorwill be set.
- creat(filename: str, mode: int) int#
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().
Added in version 2.8.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
mode – as in creat()
- Returns:
a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from creat().
- datalist_foreach(datalist: Data, func: Callable[[int, Any, Any], None], user_data: Any = None) None#
Calls the given function for each data element of the datalist. The function is called with each data element’s
Quarkid and data, together with the givenuser_dataparameter. Note that this function is NOT thread-safe. So unlessdatalistcan be protected from any modifications during invocation of this function, it should not be called.funccan make changes todatalist, but the iteration will not reflect changes made during thedatalist_foreach()call, other than skipping over elements that are removed.- Parameters:
datalist – a datalist.
func – the function to call for each data element.
user_data – user data to pass to the function.
- datalist_get_data(datalist: Data, key: str) Any | None#
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.
- Returns:
the data element, or
Noneif it is not found.
- datalist_get_flags(datalist: Data) int#
Gets flags values packed in together with the datalist. See
datalist_set_flags().Added in version 2.8.
- Parameters:
datalist – pointer to the location that holds a list
- Returns:
the flags of the datalist
- datalist_id_get_data(datalist: Data, key_id: int) Any | None#
Retrieves the data element corresponding to
key_id.- Parameters:
datalist – a datalist.
key_id – the
Quarkidentifying a data element.
- Returns:
the data element, or
Noneif it is not found.
- datalist_id_remove_multiple(datalist: Data, keys: list[int]) None#
Removes multiple keys from a datalist.
This is more efficient than calling
datalist_id_remove_data()multiple times in a row.Before 2.80,
n_keyshad to be not larger than 16. Now it can be larger, but note that GData does a linear search, so an excessive number of keys will perform badly.Added in version 2.74.
- Parameters:
datalist – a datalist
keys – keys to remove
- datalist_set_flags(datalist: Data, flags: int) None#
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
GObjecttype, for example.)Added in version 2.8.
- Parameters:
datalist – pointer to the location that holds a list
flags – the flags to turn on. The values of the flags are restricted by
DATALIST_FLAGS_MASK(currently 3; giving two possible boolean flags). A value forflagsthat doesn’t fit within the mask is an error.
- datalist_unset_flags(datalist: Data, flags: int) None#
Turns off flag values for a data list. See
datalist_unset_flags()Added in version 2.8.
- Parameters:
datalist – pointer to the location that holds a list
flags – the flags to turn off. The values of the flags are restricted by
DATALIST_FLAGS_MASK(currently 3: giving two possible boolean flags). A value forflagsthat doesn’t fit within the mask is an error.
- dataset_destroy(dataset_location: Any) None#
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(dataset_location: Any, func: Callable[[int, Any, Any], None], user_data: Any = None) None#
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_locationcan be protected from any modifications during invocation of this function, it should not be called.funccan make changes to the dataset, but the iteration will not reflect changes made during thedataset_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.
user_data – user data to pass to the function.
- dataset_id_get_data(dataset_location: Any, key_id: int) Any | None#
Gets the data element corresponding to a
Quark.- Parameters:
dataset_location – the location identifying the dataset.
key_id – the
Quarkid to identify the data element.
- Returns:
the data element corresponding to the
Quark, orNoneif it is not found.
- date_valid_weekday(weekday: DateWeekday) bool#
- Parameters:
weekday
- dcgettext(domain: str | None, msgid: str, category: int) str#
This is a variant of
dgettext()that allows specifying a locale category instead of always usingLC_MESSAGES. Seedgettext()for more information about how this functions differs from calling dcgettext() directly.Added in version 2.26.
- Parameters:
domain – the translation domain to use, or
Noneto use the domain set with textdomain()msgid – message to translate
category – a locale category
- Returns:
the translated string for the given locale category
- dgettext(domain: str | None, msgid: str) str#
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 notNonetextdomain() 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.
Added in version 2.18.
- Parameters:
domain – the translation domain to use, or
Noneto use the domain set with textdomain()msgid – message to translate
- Returns:
The translated string
- direct_equal(v1: Any = None, v2: Any = None) bool#
Compares two
gpointerarguments and returnsTrueif they are equal. It can be passed tonew()as thekey_equal_funcparameter, when using opaque pointers compared by pointer value as keys in aHashTable.This equality function is also appropriate for keys that are integers stored in pointers, such as
GINT_TO_POINTER (n).- Parameters:
v1 – a key
v2 – a key to compare with
v1
- Returns:
Trueif the two keys match.
- direct_hash(v: Any = None) int#
Converts a gpointer to a hash value. It can be passed to
new()as thehash_funcparameter, when using opaque pointers compared by pointer value as keys in aHashTable.This hash function is also appropriate for keys that are integers stored in pointers, such as
GINT_TO_POINTER (n).- Parameters:
v – a
gpointerkey- Returns:
a hash value corresponding to the key.
- dngettext(domain: str | None, msgid: str, msgid_plural: str, n: int) str#
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.Added in version 2.18.
- Parameters:
domain – the translation domain to use, or
Noneto use the domain set with textdomain()msgid – message to translate
msgid_plural – plural form of the message
n – the quantity for which translation is needed
- Returns:
The translated string
- double_equal(v1: Any, v2: Any) bool#
Compares the two
floatvalues being pointed to and returnsTrueif they are equal. It can be passed tonew()as thekey_equal_funcparameter, when using non-Nonepointers to doubles as keys in aHashTable.Added in version 2.22.
- double_hash(v: Any) int#
Converts a pointer to a
floatto a hash value. It can be passed tonew()as thehash_funcparameter, It can be passed tonew()as thehash_funcparameter, when using non-Nonepointers to doubles as keys in aHashTable.Added in version 2.22.
- Parameters:
v – a pointer to a
floatkey- Returns:
a hash value corresponding to the key.
- dpgettext(domain: str | None, msgctxtid: str, msgidoffset: int) str#
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 inmsgctxtid. If 0 is passed asmsgidoffset, 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.
Added in version 2.16.
- Parameters:
domain – the translation domain to use, or
Noneto use the domain set with textdomain()msgctxtid – a combined message context and message id, separated by a 004 character
msgidoffset – the offset of the message id in
msgctxid
- Returns:
The translated string
- dpgettext2(domain: str | None, context: str, msgid: str) str#
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 inmsgctxtid.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.
Added in version 2.18.
- Parameters:
domain – the translation domain to use, or
Noneto use the domain set with textdomain()context – the message context
msgid – the message
- Returns:
The translated string
- environ_getenv(envp: list[str] | None, variable: str) str | None#
Returns the value of the environment variable
variablein the provided listenvp.Added in version 2.32.
- Parameters:
envp – an environment list (eg, as returned from
get_environ()), orNonefor an empty environment listvariable – the environment variable to get
- Returns:
the value of the environment variable, or
Noneif the environment variable is not set inenvp. The returned string is owned byenvp, and will be freed ifvariableis set or unset again.
- environ_setenv(envp: list[str] | None, variable: str, value: str, overwrite: bool) list[str]#
Sets the environment variable
variablein the provided listenvptovalue.Added in version 2.32.
- Parameters:
envp – an environment list that can be freed using
strfreev()(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 to
overwrite – whether to change the variable if it already exists
- Returns:
the updated environment list. Free it using
strfreev().
- environ_unsetenv(envp: list[str] | None, variable: str) list[str]#
Removes the environment variable
variablefrom the provided environmentenvp.Added in version 2.32.
- Parameters:
envp – an environment list that can be freed using
strfreev()(e.g., as returned fromget_environ()), orNonefor an empty environment listvariable – the environment variable to remove, must not contain ‘=’
- Returns:
the updated environment list. Free it using
strfreev().
- error_domain_register(error_type_name: str, error_type_private_size: int, error_type_init: Callable[[GError], None], error_type_copy: Callable[[GError, GError], None], error_type_clear: Callable[[GError], None]) int#
- Parameters:
error_type_name
error_type_private_size
error_type_init
error_type_copy
error_type_clear
- error_domain_register_static(error_type_name: str, error_type_private_size: int, error_type_init: Callable[[GError], None], error_type_copy: Callable[[GError, GError], None], error_type_clear: Callable[[GError], None]) int#
- Parameters:
error_type_name
error_type_private_size
error_type_init
error_type_copy
error_type_clear
- fdwalk_set_cloexec(lowfd: int) int#
Mark every file descriptor equal to or greater than
lowfdto be closed at the nextexecve()or similar, as if via theFD_CLOEXECflag.Typically
lowfdwill 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 [callback``GLib``.SpawnChildSetupFunc], as long as
lowfdis non-negative. See`signal(7)<man:signal(7)>`__ and`signal-safety(7)<man:signal-safety(7)>`__ for more details.Added in version 2.80.
- Parameters:
lowfd – Minimum fd to act on, which must be non-negative
- Returns:
0 on success, -1 with errno set on error
- file_error_from_errno(err_no: int) FileError#
Gets a
FileErrorconstant based on the passed-inerr_no.For example, if you pass in
EEXISTthis function returnsEXIST. Unlikeerrnovalues, you can portably assume that allFileErrorvalues will exist.Normally a
FileErrorvalue goes into aErrorreturned from a function that manipulates files. So you would usefile_error_from_errno()when constructing aError.- Parameters:
err_no – an “errno” value
- Returns:
FileErrorcorresponding to the givenerr_no
- file_get_contents(filename: str) tuple[bool, list[int]]#
Reads an entire file into allocated memory, with good error checking.
If the call was successful, it returns
Trueand setscontentsto the file contents andlengthto the length of the file contents in bytes. The string stored incontentswill be nul-terminated, so for text files you can passNonefor thelengthargument. If the call was not successful, it returnsFalseand setserror. The error domain is %G_FILE_ERROR. Possible error codes are those in theFileErrorenumeration. In the error case,contentsis set toNoneandlengthis set to zero.- Parameters:
filename – name of a file to read contents from, in the GLib file name encoding
- Returns:
Trueon success,Falseif an error occurred
- file_open_tmp(tmpl: str | None = None) tuple[int, str]#
Opens a file for writing in the preferred directory for temporary files (as returned by
get_tmp_dir()).tmplshould be a string in the GLib file name encoding containing a sequence of six ‘X’ characters, as the parameter tomkstemp(). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template isNone, a default template is used.Note that in contrast to
mkstemp()(and mkstemp())tmplis not modified, and might thus be a read-only literal string.Upon success, and if
name_usedis non-None, the actual name used is returned inname_used. This string should be freed withfree()when not needed any longer. The returned name is in the GLib file name encoding.- Parameters:
tmpl – Template for file name, as in
mkstemp(), basename only, orNonefor a default template- Returns:
A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned and
errorwill be set.
- file_read_link(filename: str) str#
Reads the contents of the symbolic link
filenamelike the POSIXreadlink()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
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); }
Added in version 2.4.
- Parameters:
filename – the symbolic link
- Returns:
A newly-allocated string with the contents of the symbolic link, or
Noneif an error occurred.
- file_set_contents(filename: str, contents: list[int]) bool#
Writes all of
contentsto a file namedfilename. This is a convenience wrapper around callingfile_set_contents_full()withflagsset toG_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTINGandmodeset to0666.Added in version 2.8.
- Parameters:
filename – name of a file to write
contentsto, in the GLib file name encodingcontents – string to write to the file
- Returns:
Trueon success,Falseif an error occurred
- file_set_contents_full(filename: str, contents: list[int], flags: FileSetContentsFlags, mode: int) bool#
Writes all of
contentsto a file namedfilename, with good error checking. If a file calledfilenamealready exists it will be overwritten.flagscontrol 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
flagshas any value other thanNONEthen this function may callfsync().If
CONSISTENTis set inflags, 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 ifCONSISTENTis 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, unlessDURABLEandCONSISTENTare 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 returnsFalseand setserror. The error domain is %G_FILE_ERROR. Possible error codes are those in theFileErrorenumeration.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 may be changed tomodedepending onflags, or they may remain unchanged.Added in version 2.66.
- Parameters:
filename – name of a file to write
contentsto, in the GLib file name encodingcontents – string to write to the file
flags – flags controlling the safety vs speed of the operation
mode – file mode, as passed to
open(); typically this will be0666
- Returns:
Trueon success,Falseif an error occurred
- file_test(filename: str, test: FileTest) bool#
Returns
Trueif any of the tests in the bitfieldtestareTrue. For example,(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)will returnTrueif the file exists; the check whether it’s a directory doesn’t matter since the existence test isTrue. With the current set of available tests, there’s no point passing in more than one test at a time.Apart from
IS_SYMLINKall tests follow symbolic links, so for a symbolic link to a regular filefile_test()will returnTruefor bothIS_SYMLINKandIS_REGULAR.Note, that for a dangling symbolic link
file_test()will returnTrueforIS_SYMLINKandFalsefor 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
IS_SYMLINKto 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
EXISTSandIS_EXECUTABLEare 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
IS_SYMLINKwill always returnFalse. Testing forIS_EXECUTABLEwill just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in thePATHEXTenvironment variable.- Parameters:
filename – a filename to test in the GLib file name encoding
test – bitfield of
FileTestflags
- Returns:
whether a test was
True
- filename_display_basename(filename: str) str#
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 “357277275” in octal notation) to find out iffilenamewas 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.Added in version 2.6.
- Parameters:
filename – an absolute pathname in the GLib file name encoding
- Returns:
a newly allocated string containing a rendition of the basename of the filename in valid UTF-8
- filename_display_name(filename: str) str#
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-Noneeven 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 “357277275” in octal notation) to find out iffilenamewas 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.Added in version 2.6.
- Parameters:
filename – a pathname hopefully in the GLib file name encoding
- Returns:
a newly allocated string containing a rendition of the filename in valid UTF-8
- filename_from_uri(uri: str) tuple[str, str | None]#
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).
- Returns:
a newly-allocated string holding the resulting filename, or
Noneon an error.
- filename_from_utf8(utf8string, len=-1)#
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][setlocale].
The input string shall not contain nul characters even if the
lenargument is positive. A nul character found inside the string will result in errorILLEGAL_SEQUENCE. If the filename encoding is not UTF-8 and the conversion output contains a nul character, the errorEMBEDDED_NULis set and the function returnsNone.- Parameters:
utf8string – a UTF-8 encoded string.
len – the length of the string, or -1 if the string is nul-terminated.
- Returns:
The converted string, or
Noneon an error.
- filename_to_uri(filename: str, hostname: str | None = 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 Windows
hostname – A UTF-8 encoded hostname, or
Nonefor none.
- Returns:
a newly-allocated string holding the resulting URI, or
Noneon an error.
- filename_to_utf8(opsysstring: str, 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][setlocale].
The input string shall not contain nul characters even if the
lenargument is positive. A nul character found inside the string will result in errorILLEGAL_SEQUENCE. If the source encoding is not UTF-8 and the conversion output contains a nul character, the errorEMBEDDED_NULis set and the function returnsNone. Useconvert()to produce output that may contain embedded nul characters.- Parameters:
opsysstring – a string in the encoding for filenames
len – 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 the
lenparameter is unsafe)
- Returns:
The converted string, or
Noneon an error.
- find_program_in_path(program: str) str | None#
Locates the first executable named
programin the user’s path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, orNoneif the program is not found in the path. Ifprogramis already an absolute path, returns a copy ofprogramifprogramexists and is executable, andNoneotherwise.On Windows, if
programdoes not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in thePATHEXTenvironment 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
PATHenvironment 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
- Returns:
a newly-allocated string with the absolute path, or
None
- fopen(filename: str, mode: str) Any | None#
A wrapper for the stdio
fopen()function. Thefopen()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
FILEstruct, theFILE*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 likefprintf()orfread().See your C library manual for more details about
fopen().As
close()andfclose()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 likefile_set_contents_full()avoid this problem.Added in version 2.6.
- 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
- Returns:
A
FILE*if the file was successfully opened, orNoneif an error occurred
- format_size(size: int) str#
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.Added in version 2.30.
- Parameters:
size – a size in bytes
- Returns:
a newly-allocated formatted string containing a human readable file size
- format_size_for_display(size: int) str#
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.Added in version 2.16.
Deprecated since version 2.30: This function is broken due to its use of SI suffixes to denote IEC units. Use
format_size()instead.- Parameters:
size – a size in bytes
- Returns:
a newly-allocated formatted string containing a human readable file size
- format_size_full(size: int, flags: FormatSizeFlags) str#
Formats a size.
This function is similar to
format_size()but allows for flags that modify the output. SeeFormatSizeFlags.Added in version 2.30.
- Parameters:
size – a size in bytes
flags –
FormatSizeFlagsto modify the output
- Returns:
a newly-allocated formatted string containing a human readable file size
- free(mem: Any = None) None#
Frees the memory pointed to by
mem.If you know the allocated size of
mem, callingfree_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()`<https://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html>`__ to understand its caveats).If
memisNoneit simply returns, so there is no need to checkmemagainstNonebefore calling this function.- Parameters:
mem – the memory to free
- free_sized(mem: Any, size: int) None#
Frees the memory pointed to by
mem, assuming it is has the givensize.If
memisNonethis is a no-op (andsizeis ignored).It is an error if
sizedoesn’t match the size passed whenmemwas allocated.sizeis passed to this function to allow optimizations in the allocator. If you don’t know the allocation size, usefree()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.Added in version 2.76.
- Parameters:
mem – the memory to free
size – size of
mem, in bytes
- freopen(filename: str, mode: str, stream: Any = None) Any | 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().
Added in version 2.6.
- 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
stream – an existing stream which will be reused, or
None
- Returns:
A FILE* if the file was successfully opened, or
Noneif an error occurred.
- fsync(fd: int) int#
A wrapper for the POSIX
fsync()function. On Windows,_commit()will be used. On macOS,fcntl(F_FULLFSYNC)will be used. Thefsync()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().
Added in version 2.64.
- Parameters:
fd – a file descriptor
- Returns:
0 on success, or -1 if an error occurred. The return value can be used exactly like the return value from fsync().
- get_application_name() str | None#
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 withget_prgname(), which gets a non-localized name. Ifset_application_name()has not been called, returns the result ofget_prgname()(which may beNoneifset_prgname()has also not been called).Added in version 2.2.
- Returns:
human-readable application name. May return
None
- get_charset() tuple[bool, str]#
Obtains the character set for the [current locale][setlocale]; you might use this character set as an argument to
convert(), to convert from the current locale’s encoding to some other encoding. (Frequentlylocale_to_utf8()andlocale_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,LANGandCHARSETare queried in order. nl_langinfo() returns the C locale if no locale has been loaded by setlocale().The return value is
Trueif the locale’s encoding is UTF-8, in that case you can perhaps avoid callingconvert().The string returned in
charsetis not allocated, and should not be freed.- Returns:
Trueif the returned charset is UTF-8
- get_codeset() str#
Gets the character set for the current locale.
- Returns:
a newly allocated string containing the name of the character set. This string must be freed with
free().
- get_console_charset() tuple[bool, str]#
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
Trueif the locale’s encoding is UTF-8, in that case you can perhaps avoid callingconvert().The string returned in
charsetis not allocated, and should not be freed.Added in version 2.62.
- Returns:
Trueif the returned charset is UTF-8
- get_current_dir() str#
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.
- Returns:
the current directory
- get_current_time()#
Equivalent to the UNIX gettimeofday() function, but portable.
You may find
get_real_timeto be more convenient.Deprecated since version 2.62:
TimeValis not year-2038-safe. Useget_real_timeinstead.
- get_environ() list[str]#
Gets the list of environment variables for the current process.
The list is
Noneterminated 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.Added in version 2.28.
- Returns:
the list of environment variables
- get_filename_charsets() tuple[bool, list[str]]#
Determines the preferred character sets used for filenames. The first character set from the
charsetsis the filename encoding, the subsequent character sets are used when trying to generate a displayable representation of a filename, seefilename_display_name().On Unix, the character sets are determined by consulting the environment variables
G_FILENAME_ENCODINGandG_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_ENCODINGmay 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][setlocale]. IfG_FILENAME_ENCODINGis not set, butG_BROKEN_FILENAMESis, 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
charsetsbelong to GLib and must not be freed.Note that on Unix, regardless of the locale character set or
G_FILENAME_ENCODINGvalue, the actual file names present on a system might be in any random encoding or just gibberish.Added in version 2.6.
- Returns:
Trueif the filename encoding is UTF-8.
- get_home_dir() str#
Gets the current user’s home directory.
As with most UNIX tools, this function will return the value of the
HOMEenvironment variable if it is set to an existing absolute path name, falling back to thepasswdfile in the case that it is unset.If the path given in
HOMEis non-absolute, does not exist, or is not a directory, the result is undefined.Before version 2.36 this function would ignore the
HOMEenvironment variable, taking the value from thepasswddatabase 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
HOMEenvironment variable yourself or unset it before calling any functions in GLib.- Returns:
the current user’s home directory
- get_host_name() str#
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.
Added in version 2.8.
- Returns:
the host name of the machine.
- get_language_names() list[str]#
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_MESSAGESandLANGto find the list of locales specified by the user.Added in version 2.6.
- Returns:
a
None-terminated array of strings owned by GLib that must not be modified or freed.
- get_language_names_with_category(category_name: str) list[str]#
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, andLANGto find the list of locales specified by the user.get_language_names()returns g_get_language_names_with_category(“LC_MESSAGES”).Added in version 2.58.
- Parameters:
category_name – a locale category name
- Returns:
a
None-terminated array of strings owned by the thread g_get_language_names_with_category was called from. It must not be modified or freed. It must be copied if planned to be used in another thread.
- get_locale_variants(locale: str) list[str]#
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)<man:setlocale>`__ for information about locales and their format.localeitself is guaranteed to be returned in the output.For example, if
localeisfr_BE, then the returned list isfr_BE,fr. Iflocaleisen_GB.UTF-8@euro, then the returned list isen_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().Added in version 2.28.
- Parameters:
locale – a locale identifier
- Returns:
a newly allocated array of newly allocated strings with the locale variants. Free with
strfreev().
- get_monotonic_time() int#
Queries the system monotonic time.
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.
Added in version 2.28.
- Returns:
the monotonic time, in microseconds
- get_num_processors() int#
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
new()for CPU bound tasks and similar cases.Added in version 2.36.
- Returns:
Number of schedulable threads, always greater than 0
- get_os_info(key_name: str) str | None#
Get information about the operating system.
On Linux this comes from the
/etc/os-releasefile. 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-releaseprovides 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 isNone.Added in version 2.64.
- Parameters:
key_name – a key for the OS info being requested, for example %G_OS_INFO_KEY_NAME.
- Returns:
The associated value for the requested key or
Noneif this information is not provided.
- get_prgname() str | None#
Gets the name of the program. This name should not be localized, in contrast to
get_application_name().If you are using
GApplicationthe program name is set in g_application_run(). In case of GDK or GTK it is set in gdk_init(), which is called by gtk_init() and theGtkApplication::startup handler. The program name is found by taking the last component ofargv[0].- Returns:
the name of the program, or
Noneif it has not been set yet. The returned string belongs to GLib and must not be modified or freed.
- get_real_name() str#
Gets the real name of the user. This usually comes from the user’s entry in the
passwdfile. 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.- Returns:
the user’s real name.
- get_real_time() int#
Queries the system wall-clock time.
This call is functionally equivalent to
get_current_timeexcept that the return value is often more convenient than dealing with aTimeVal.You should only use this call if you are actually interested in the real wall-clock time.
get_monotonic_timeis probably more useful for measuring intervals.Added in version 2.28.
- Returns:
the number of microseconds since January 1, 1970 UTC.
- get_system_config_dirs() list[str]#
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_DIRSis defined. IfXDG_CONFIG_DIRSis undefined, the directory that contains application data for all users is used instead. A typical path isC:\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.
Added in version 2.6.
- Returns:
a
None-terminated array of strings owned by GLib that must not be modified or freed.
- get_system_data_dirs() list[str]#
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_DIRSis defined. IfXDG_DATA_DIRSis 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.
Added in version 2.6.
- Returns:
a
None-terminated array of strings owned by GLib that must not be modified or freed.
- get_tmp_dir() str#
Gets the directory to use for temporary files.
On UNIX, this is taken from the
TMPDIRenvironment variable. If the variable is not set,P_tmpdiris used, as defined by the system C library. Failing that, a hard-coded default of “/tmp” is returned.On Windows, the
TEMPenvironment 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
Noneor the empty string.- Returns:
the directory to use for temporary files.
- get_user_cache_dir() str#
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_HOMEis defined. IfXDG_CACHE_HOMEis undefined, the directory that serves as a common repository for temporary Internet files is used instead. A typical path isC:\Documents and Settings\username\Local Settings\Temporary Internet Files. See thedocumentation for ``FOLDERID_InternetCache`<https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid>`__.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.
Added in version 2.6.
- Returns:
a string owned by GLib that must not be modified or freed.
- get_user_config_dir() str#
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_HOMEis defined. IfXDG_CONFIG_HOMEis undefined, the folder to use for local (as opposed to roaming) application data is used instead. See thedocumentation for ``FOLDERID_LocalAppData`<https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid>`__. Note that in this case on Windows it will be the same as whatget_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.
Added in version 2.6.
- Returns:
a string owned by GLib that must not be modified or freed.
- get_user_data_dir() str#
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_HOMEis defined. IfXDG_DATA_HOMEis undefined, the folder to use for local (as opposed to roaming) application data is used instead. See thedocumentation for ``FOLDERID_LocalAppData`<https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid>`__. Note that in this case on Windows it will be the same as whatget_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.
Added in version 2.6.
- Returns:
a string owned by GLib that must not be modified or freed.
- get_user_name() str#
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.
- Returns:
the user name of the current user.
- get_user_runtime_dir() str#
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_DIRenvironment variable. In the case that this variable is not set, we return the value ofget_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.
Added in version 2.28.
- Returns:
a string owned by GLib that must not be modified or freed.
- get_user_special_dir(directory: UserDirectory) str | None#
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,
DIRECTORY_DESKTOPfalls back to$HOME/Desktopwhen 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.
Added in version 2.14.
- Parameters:
directory – the logical id of special directory
- Returns:
the path to the specified special directory, or
Noneif the logical id was not found. The returned string is owned by GLib and should not be modified or freed.
- get_user_state_dir() str#
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_HOMEis defined. IfXDG_STATE_HOMEis undefined, the folder to use for local (as opposed to roaming) application data is used instead. See thedocumentation for ``FOLDERID_LocalAppData`<https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid>`__. Note that in this case on Windows it will be the same as whatget_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.
Added in version 2.72.
- Returns:
a string owned by GLib that must not be modified or freed.
- getenv(variable: str) str | None#
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
- Returns:
the value of the environment variable, or
Noneif the environment variable is not found. The returned string may be overwritten by the next call togetenv(),setenv()orunsetenv().
- hash_table_find(hash_table: dict[Any, Any], predicate: Callable[[Any, Any, Any], bool], user_data: Any = None) Any | None#
- Parameters:
hash_table
predicate
user_data
- hash_table_foreach(hash_table: dict[Any, Any], func: Callable[[Any, Any, Any], None], user_data: Any = None) None#
- Parameters:
hash_table
func
user_data
- hash_table_foreach_remove(hash_table: dict[Any, Any], func: Callable[[Any, Any, Any], bool], user_data: Any = None) int#
- Parameters:
hash_table
func
user_data
- hash_table_insert(hash_table: dict[Any, Any], key: Any = None, value: Any = None) bool#
- Parameters:
hash_table
key
value
- hash_table_lookup(hash_table: dict[Any, Any], key: Any = None) Any | None#
- Parameters:
hash_table
key
- hash_table_lookup_extended(hash_table: dict[Any, Any], lookup_key: Any = None) tuple[bool, Any | None, Any | None]#
- Parameters:
hash_table
lookup_key
- hash_table_new_similar(other_hash_table: dict[Any, Any]) dict[Any, Any]#
- Parameters:
other_hash_table
- hash_table_replace(hash_table: dict[Any, Any], key: Any = None, value: Any = None) bool#
- Parameters:
hash_table
key
value
- hook_insert_before(hook_list: HookList, sibling: Hook | None, hook: Hook) None#
- Parameters:
hook_list
sibling
hook
- hook_insert_sorted(hook_list: HookList, hook: Hook, func: Callable[[Hook, Hook], int]) None#
- Parameters:
hook_list
hook
func
- hostname_is_ascii_encoded(hostname: str) bool#
Tests if
hostnamecontains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returnsTrue, you should decode the hostname withhostname_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()andhostname_is_ascii_encoded()to both returnTruefor a name.Added in version 2.22.
- Parameters:
hostname – a hostname
- Returns:
Trueifhostnamecontains any ASCII-encoded segments.
- hostname_is_ip_address(hostname: str) bool#
Tests if
hostnameis 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).
Added in version 2.22.
- Parameters:
hostname – a hostname (or IP address in string form)
- Returns:
Trueifhostnameis an IP address
- hostname_is_non_ascii(hostname: str) bool#
Tests if
hostnamecontains Unicode characters. If this returnsTrue, you need to encode the hostname withhostname_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()andhostname_is_ascii_encoded()to both returnTruefor a name.Added in version 2.22.
- Parameters:
hostname – a hostname
- Returns:
Trueifhostnamecontains any non-ASCII characters
- hostname_to_ascii(hostname: str) str | None#
Converts
hostnameto its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot.Added in version 2.22.
- Parameters:
hostname – a valid UTF-8 or ASCII hostname
- Returns:
an ASCII hostname, which must be freed, or
Noneifhostnameis in some way invalid.
- hostname_to_unicode(hostname: str) str | None#
Converts
hostnameto 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
hostnameis not an internationalized hostname, then the canonical presentation form will be entirely ASCII.Added in version 2.22.
- Parameters:
hostname – a valid UTF-8 or ASCII hostname
- Returns:
a UTF-8 hostname, which must be freed, or
Noneifhostnameis in some way invalid.
- idle_add(function, *user_data, priority=200)#
Adds a function to be called whenever there are no higher priority events pending to the default main loop. The function is given the default idle priority,
PRIORITY_DEFAULT_IDLE. If the function returnsFalseit is automatically removed from the list of event sources and will not be called again.See mainloop 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_newand attaches it to the globalMainContextusingattach, 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:
function – function to call
user_data
priority
- Returns:
the ID (greater than 0) of the event source.
- idle_remove_by_data(data: Any = None) bool#
Removes the idle function with the given data.
- Parameters:
data – the data for the idle source’s callback.
- Returns:
Trueif an idle source was found and removed.
- idle_source_new() Source#
Creates a new idle source.
The source will not initially be associated with any
MainContextand must be added to one withattachbefore it will be executed. Note that the default priority for idle sources isPRIORITY_DEFAULT_IDLE, as compared to other sources which have a default priority ofPRIORITY_DEFAULT.- Returns:
the newly-created idle source
- int64_equal(v1: Any, v2: Any) bool#
Compares the two
intvalues being pointed to and returnsTrueif they are equal. It can be passed tonew()as thekey_equal_funcparameter, when using non-Nonepointers to 64-bit integers as keys in aHashTable.Added in version 2.22.
- int64_hash(v: Any) int#
Converts a pointer to a
intto a hash value.It can be passed to
new()as thehash_funcparameter, when using non-Nonepointers to 64-bit integer values as keys in aHashTable.Added in version 2.22.
- Parameters:
v – a pointer to a
intkey- Returns:
a hash value corresponding to the key.
- int_equal(v1: Any, v2: Any) bool#
Compares the two
intvalues being pointed to and returnsTrueif they are equal. It can be passed tonew()as thekey_equal_funcparameter, when using non-Nonepointers to integers as keys in aHashTable.Note that this function acts on pointers to
int, not onintdirectly: if your hash table’s keys are of the formGINT_TO_POINTER (n), usedirect_equal()instead.
- int_hash(v: Any) int#
Converts a pointer to a
intto a hash value. It can be passed tonew()as thehash_funcparameter, when using non-Nonepointers to integer values as keys in aHashTable.Note that this function acts on pointers to
int, not onintdirectly: if your hash table’s keys are of the formGINT_TO_POINTER (n), usedirect_hash()instead.- Parameters:
v – a pointer to a
intkey- Returns:
a hash value corresponding to the key.
- intern_static_string(string: str | None = None) str#
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, thereforestringmust 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++.
Added in version 2.10.
- Parameters:
string – a static string
- Returns:
a canonical representation for the string
- intern_string(string: str | None = None) str#
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++.
Added in version 2.10.
- Parameters:
string – a string
- Returns:
a canonical representation for the string
- io_add_watch(*args, **kwargs)#
Adds the
IOChannelinto the default main loop context with the default priority.- Parameters:
args
kwargs
- Returns:
the event source id
- io_channel_error_from_errno(en: int) IOChannelError#
- Parameters:
en
- io_create_watch(channel: IOChannel, condition: IOCondition) Source#
Creates a
Sourcethat’s dispatched whenconditionis met for the givenchannel. For example, if condition isIN, the source will be dispatched when there’s data available for reading.The callback function invoked by the
Sourceshould be added withset_callback(), but it has typeIOFunc(notSourceFunc).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
Sourcecreated to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.
- listenv() list[str]#
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 andgetenv()provide.Added in version 2.8.
- Returns:
a
None-terminated list of strings which must be freed withstrfreev().
- locale_from_utf8(utf8string: str, len: int) tuple[list[int], int]#
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][setlocale]. On Windows this means the system codepage.
The input string shall not contain nul characters even if the
lenargument is positive. A nul character found inside the string will result in errorILLEGAL_SEQUENCE. Useconvert()to convert input that may contain embedded nul characters.- Parameters:
utf8string – a UTF-8 encoded string
len – the length of the string, or -1 if the string is nul-terminated.
- Returns:
A newly-allocated buffer containing the converted string, or
Noneon an error, and error will be set.
- locale_to_utf8(opsysstring: list[int]) tuple[str, int, int]#
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][setlocale] into a UTF-8 string.
If the source encoding is not UTF-8 and the conversion output contains a nul character, the error
EMBEDDED_NULis set and the function returnsNone. If the source encoding is UTF-8, an embedded nul character is treated with theILLEGAL_SEQUENCEerror for backward compatibility with earlier versions of this library. Useconvert()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.
- Returns:
The converted string, or
Noneon an error.
- log_default_handler(log_domain: str | None, log_level: LogLevelFlags, message: str | None = None, unused_data: Any = None) None#
The default log handler set up by GLib;
log_set_default_handlerallows 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
stderrorstdoutand if the log level is fatal it callsBREAKPOINT. It automatically prints a new-line character after the message, so one does not need to be manually included inmessage.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 whichmessages should be prefixed by the program name and PID of the application.
G_MESSAGES_DEBUG: A space-separated list of log domains forwhich debug and informational messages are printed. By default these messages are not printed. If you need to set the allowed domains at runtime, use
log_writer_default_set_debug_domains.
stderris used for levelsLEVEL_ERROR,LEVEL_CRITICAL,LEVEL_WARNINGandLEVEL_MESSAGE.stdoutis used for the rest, unlessstderrwas requested bylog_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, or
NULLfor the default""application domainlog_level – the level of the message
message – the message
unused_data – data passed from
logwhich is unused
- log_get_debug_enabled() bool#
Return whether debug output from the GLib logging system is enabled.
Note that this should not be used to conditionalise calls to
debugor other logging functions; it should only be used fromLogWriterFuncimplementations.Note also that the value of this does not depend on
G_MESSAGES_DEBUG, norlog_writer_default_set_debug_domains; see the docs forlog_set_debug_enabled.Added in version 2.72.
- Returns:
TRUEif debug output is enabled,FALSEotherwise
- log_remove_handler(log_domain: str, handler_id: int) None#
Removes the log handler.
This has no effect if structured logging is enabled; see Using Structured Logging.
- Parameters:
log_domain – the log domain
handler_id – the ID of the handler, which was returned in
log_set_handler
- log_set_always_fatal(fatal_mask: LogLevelFlags) LogLevelFlags#
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.
LEVEL_ERRORis always fatal.You can also make some message levels fatal at runtime by setting the
G_DEBUGenvironment 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
log_structuredandlog_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
- Returns:
the old fatal mask
- log_set_debug_enabled(enabled: bool) None#
Enable or disable debug output from the GLib logging system for all domains.
This value interacts disjunctively with
G_MESSAGES_DEBUGandlog_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.
Added in version 2.72.
- Parameters:
enabled –
TRUEto enable debug output,FALSEotherwise
- log_set_fatal_mask(log_domain: str, fatal_mask: LogLevelFlags) LogLevelFlags#
Sets the log levels which are fatal in the given domain.
LEVEL_ERRORis always fatal.This has no effect on structured log messages (using
log_structuredorlog_structured_array). To change the fatal behaviour for specific log messages, programs must install a custom log writer function usinglog_set_writer_func. See Using Structured Logging.This function is mostly intended to be used with
LEVEL_CRITICAL. You should typically not setLEVEL_WARNING,LEVEL_MESSAGE,LEVEL_INFOorLEVEL_DEBUGas fatal except inside of test programs.- Parameters:
log_domain – the log domain
fatal_mask – the new fatal mask
- Returns:
the old fatal mask for the log domain
- log_set_handler(log_domain: str | None, log_levels: LogLevelFlags, log_func: Callable[[str, LogLevelFlags, str, Any], None], user_data: Any = None) int#
Sets the log handler for a domain and a set of log levels.
To handle fatal and recursive messages the
log_levelsparameter must be combined with theFLAG_FATALandFLAG_RECURSIONbit flags.Note that since the
LEVEL_ERRORlog level is always fatal, if you want to set a handler for this log level you must combine it withFLAG_FATAL.This has no effect if structured logging is enabled; see Using Structured Logging.
Here is an example for adding a log handler for all warning messages in the default domain:
g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
This example adds a log handler for all critical messages from GTK:
g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
This example adds a log handler for all messages from GLib:
g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
- Parameters:
log_domain – the log domain, or
NULLfor the default""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 the
FLAG_FATALandFLAG_RECURSIONbit flags.log_func – the log handler function
user_data – data passed to the log handler
- Returns:
the id of the new handler
- log_set_writer_func(user_data: Any = None) None#
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.
Added in version 2.50.
- Parameters:
user_data – user data to pass to
func
- log_structured_array(log_level: LogLevelFlags, fields: list[LogField]) None#
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 isLEVEL_ERROR), the program will be aborted at the end of this function.See
log_structuredfor more documentation.This assumes that
log_levelis already present infields(typically as thePRIORITYfield).Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags, or a user-defined levelfields – key–value pairs of structured data to add to the log message
- log_variant(log_domain: str | None, log_level: LogLevelFlags, fields: Variant) None#
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
fieldsdictionary is the"MESSAGE"which must contain the text shown to the user.The values in the
fieldsdictionary are likely to be of typeG_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 thanG_MAXSSIZE. Otherwise it will be truncated to this size. For other typesprintwill be used to convert the value into a string.For more details on its usage and about the parameters, see
log_structured.Added in version 2.50.
- Parameters:
log_domain – log domain, usually
G_LOG_DOMAINlog_level – log level, either from
LogLevelFlags, or a user-defined levelfields – a dictionary (
Variantof the typeG_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.
- log_writer_default(log_level: LogLevelFlags, fields: list[LogField], user_data: Any = 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
stdoutorstderrif 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 usinglog_set_writer_func.As with
log_default_handler, this function drops debug and informational messages unless their log domain (orall) is listed in the space-separatedG_MESSAGES_DEBUGenvironment variable, or set at runtime bylog_writer_default_set_debug_domains.log_writer_defaultuses the mask set bylog_set_always_fatalto 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.Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags, or a user-defined levelfields – key–value pairs of structured data forming the log message
user_data – user data passed to
log_set_writer_func
- Returns:
- log_writer_default_set_debug_domains(domains: str | None = None) None#
Reset the list of domains to be logged, that might be initially set by the
G_MESSAGES_DEBUGenvironment variable.This function is thread-safe.
Added in version 2.80.
- 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(use_stderr: bool) None#
Configure whether the built-in log functions will output all log messages to
stderr.The built-in log functions are
log_default_handlerfor the old-style API, and bothlog_writer_defaultandlog_writer_standard_streamsfor the structured API.By default, log messages of levels
LEVEL_INFOandLEVEL_DEBUGare sent tostdout, and other log messages are sent tostderr. This is problematic for applications that intend to reservestdoutfor 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.
Added in version 2.68.
- Parameters:
use_stderr – If
TRUE, usestderrfor log messages that would normally have appeared onstdout
- log_writer_default_would_drop(log_level: LogLevelFlags, log_domain: str | None = None) bool#
Check whether
log_writer_defaultandlog_default_handlerwould 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 (orall) is listed in the space-separatedG_MESSAGES_DEBUGenvironment variable, or bylog_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` is not set: ```c if (!g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN)) { g_autofree gchar *result = expensive_computation (my_object); g_debug ("my_object result: %s", result); }
Added in version 2.68.
- Parameters:
log_level – log level, either from
LogLevelFlags, or a user-defined levellog_domain – log domain
- Returns:
TRUEif the log message would be dropped by GLib’s default log handlers
- log_writer_format_fields(log_level: LogLevelFlags, 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
MESSAGEandGLIB_DOMAIN(see the documentation forlog_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.
Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags, or a user-defined levelfields – key–value pairs of structured data forming the log message
use_color –
TRUEto use ANSI color escape sequences when formatting the message,FALSEto not
- Returns:
string containing the formatted log message, in the character set of the current locale
- log_writer_is_journald(output_fd: int) bool#
Check whether the given
output_fdfile descriptor is a connection to the systemd journal, or something else (like a log file orstdoutorstderr).Invalid file descriptors are accepted and return
FALSE, which allows for the following construct without needing any additional error handling:is_journald = g_log_writer_is_journald (fileno (stderr));
Added in version 2.50.
- Parameters:
output_fd – output file descriptor to check
- Returns:
TRUEifoutput_fdpoints to the journal,FALSEotherwise
- log_writer_journald(log_level: LogLevelFlags, fields: list[LogField], user_data: Any = 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
UNHANDLED.Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags, or a user-defined levelfields – key–value pairs of structured data forming the log message
user_data – user data passed to
log_set_writer_func
- Returns:
- log_writer_standard_streams(log_level: LogLevelFlags, fields: list[LogField], user_data: Any = None) LogWriterOutput#
Format a structured log message and print it to either
stdoutorstderr, depending on its log level.LEVEL_INFOandLEVEL_DEBUGmessages are sent tostdout, or tostderrif requested bylog_writer_default_set_use_stderr; all other log levels are sent tostderr. 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.Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags, or a user-defined levelfields – key–value pairs of structured data forming the log message
user_data – user data passed to
log_set_writer_func
- Returns:
- log_writer_supports_color(output_fd: int) bool#
Check whether the given
output_fdfile descriptor supports ANSI color escape sequences.If so, they can safely be used when formatting log messages.
Added in version 2.50.
- Parameters:
output_fd – output file descriptor to check
- Returns:
TRUEif ANSI color escapes are supported,FALSEotherwise
- log_writer_syslog(log_level: LogLevelFlags, fields: list[LogField], user_data: Any = 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
UNHANDLED.Added in version 2.80.
- Parameters:
log_level – log level, either from
LogLevelFlags, or a user-defined levelfields – key–value pairs of structured data forming the log message
user_data – user data passed to
log_set_writer_func
- Returns:
- lstat(filename: str, buf: StatBuf) int#
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 tostat().See your C library manual for more details about lstat().
Added in version 2.6.
- 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
- Returns:
0 if the information was successfully retrieved, -1 if an error occurred
- main_context_default() MainContext#
- main_context_get_thread_default() MainContext | None#
- main_current_source() Source | None#
Returns the currently firing source for this thread.
Added in version 2.12.
- Returns:
The currently firing source or
None.
- main_depth() int#
Returns the depth of the stack of calls to
dispatchon anyMainContextin the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback fromiteration(orrun, etc.) it returns 1. When called from within a callback to a recursive call toiteration, 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_depthgpointer 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_depthto 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 ifmain_depthreturns 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.
- Returns:
The main loop recursion level in the current thread
- malloc(n_bytes: int) Any | None#
Allocates
n_bytesbytes of memory. Ifn_bytesis 0 it returnsNone.If the allocation fails (because the system is out of memory), the program is terminated.
- Parameters:
n_bytes – the number of bytes to allocate
- Returns:
a pointer to the allocated memory
- malloc0(n_bytes: int) Any | None#
Allocates
n_bytesbytes of memory, initialized to 0’s. Ifn_bytesis 0 it returnsNone.If the allocation fails (because the system is out of memory), the program is terminated.
- Parameters:
n_bytes – the number of bytes to allocate
- Returns:
a pointer to the allocated memory
- malloc0_n(n_blocks: int, n_block_bytes: int) Any | None#
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.
Added in version 2.24.
- Parameters:
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
- Returns:
a pointer to the allocated memory
- malloc_n(n_blocks: int, n_block_bytes: int) Any | None#
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.
Added in version 2.24.
- Parameters:
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
- Returns:
a pointer to the allocated memory
- markup_escape_text(text, length=-1)#
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 wzxhzdk:0 … wzxhzdk:1 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 text
length – length of
textin bytes, or -1 if the text is nul-terminated
- Returns:
a newly allocated string with the escaped text
- mem_is_system_malloc() bool#
Checks whether the allocator used by
malloc()is the system’s malloc implementation. If it returnsTruememory allocated with malloc() can be used interchangeably with memory allocated usingmalloc(). This function is useful for avoiding an extra copy of allocated memory returned by a non-GLib-based API.Deprecated since version 2.46: GLib always uses the system malloc, so this function always returns
True.- Returns:
if
True, malloc() andmalloc()can be mixed.
- mem_profile() None#
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.
Deprecated since version 2.46: Use other memory profiling tools instead
- mem_set_vtable(vtable: MemVTable) None#
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.
Deprecated since version 2.46: This function now does nothing. Use other memory profiling tools instead
- Parameters:
vtable – table of memory allocation routines.
- memdup(mem: Any, byte_size: int) Any | None#
Allocates
byte_sizebytes of memory, and copiesbyte_sizebytes into it frommem. IfmemisNULLit returnsNULL.Deprecated since version 2.68: Use
memdup2instead, as it accepts a gsize argument forbyte_size, avoiding the possibility of overflow in agsize→guintconversion- Parameters:
mem – the memory to copy
byte_size – the number of bytes to copy
- Returns:
a pointer to the newly-allocated copy of the memory
- memdup2(mem: Any, byte_size: int) Any | None#
Allocates
byte_sizebytes of memory, and copiesbyte_sizebytes into it frommem. IfmemisNULLit returnsNULL.This replaces
memdup, which was prone to integer overflows when converting the argument from agsizeto aguint.Added in version 2.68.
- Parameters:
mem – the memory to copy
byte_size – the number of bytes to copy
- Returns:
a pointer to the newly-allocated copy of the memory
- mkdir(filename: str, mode: int) int#
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().
Added in version 2.6.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
mode – permissions to use for the newly created directory
- Returns:
0 if the directory was successfully created, -1 if an error occurred
- mkdir_with_parents(pathname: str, mode: int) int#
Create a directory if it doesn’t already exist. Create intermediate parent directories as needed, too.
Added in version 2.8.
- Parameters:
pathname – a pathname in the GLib file name encoding
mode – permissions to use for newly created directories
- Returns:
0 if the directory already exists, or was successfully created. Returns -1 if an error occurred, with errno set.
- nullify_pointer(nullify_location: Any) None#
Set the pointer at the specified location to
None.- Parameters:
nullify_location – the memory address of the pointer.
- on_error_query(prg_name: str) None#
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 thelog()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_DEBUGGERenvironment variable (see Running GLib Applications) and callingon_error_stack_trace()instead.- Parameters:
prg_name – the program name, needed by gdb for the “[S]tack trace” option. If
prg_nameisNone,get_prgname()is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called)
- on_error_stack_trace(prg_name: str) None#
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 withget_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 theG_DEBUGGERenvironment 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
- open(filename: str, 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().
Added in version 2.6.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
flags – as in open()
mode – as in open()
- Returns:
a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from open().
- parse_debug_string(string: str | None, keys: list[DebugKey]) int#
Parses a string containing debugging options into a unsigned
intcontaining bit flags. This is used within GDK and GTK to parse the debug options passed on the command line or through environment variables.If
stringis equal to “all”, all flags are set. Any flags specified along with “all” instringare inverted; thus, “all,foo,bar” or “foo,bar,all” sets all flags except those corresponding to “foo” and “bar”.If
stringis equal to “help”, all the available keys inkeysare printed out to standard error.- Parameters:
string – a list of debug options separated by colons, spaces, or commas, or
None.keys – pointer to an array of
DebugKeywhich associate strings with bit flags.
- Returns:
the combined set of bit flags.
- path_get_basename(file_name: str) str#
Gets the last component of the filename.
If
file_nameends with a directory separator it gets the component before the last slash. Iffile_nameconsists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. Iffile_nameis empty, it gets “.”.- Parameters:
file_name – the name of the file
- Returns:
a newly allocated string containing the last component of the filename
- path_get_dirname(file_name: str) str#
Gets the directory components of a file name. For example, the directory component of
/usr/bin/testis/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
- Returns:
the directory components of the file
- path_is_absolute(file_name: str) bool#
Returns
Trueif the givenfile_nameis 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 “Userstml” or begins with the root on a drive, for example “C:Windows”. The first case also includes UNC paths such as “\myserverdocsfoo”. 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
- Returns:
Trueiffile_nameis absolute
- path_skip_root(file_name: str) str | None#
Returns a pointer into
file_nameafter the root component, i.e. after the “/” in UNIX or “C:" under Windows. Iffile_nameis not an absolute path it returnsNone.- Parameters:
file_name – a file name
- Returns:
a pointer into
file_nameafter the root component
- pattern_match_simple(pattern: str, string: str) bool#
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
newand callmatch_stringrepeatedly.- Parameters:
pattern – the UTF-8 encoded pattern
string – the UTF-8 encoded string to match
- Returns:
Trueifstringmatchespspec
- pointer_bit_lock(address: Any, lock_bit: int) None#
This is equivalent to g_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
addresshas avolatilequalifier, this is a historical artifact and the argument passed to it should not bevolatile.Added in version 2.30.
- Parameters:
address – a pointer to a
gpointer-sized valuelock_bit – a bit value between 0 and 31
- pointer_bit_lock_and_get(address: Any, lock_bit: int) int#
This is equivalent to g_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.
Added in version 2.80.
- Parameters:
address – a pointer to a
gpointer-sized valuelock_bit – a bit value between 0 and 31
- pointer_bit_lock_mask_ptr(ptr: Any, lock_bit: int, set: bool, preserve_mask: int, preserve_ptr: Any = None) Any | None#
This mangles
ptraspointer_bit_lock()andpointer_bit_unlock()do.Added in version 2.80.
- Parameters:
ptr – the pointer to mask
lock_bit – the bit to set/clear. If set to
G_MAXUINT, the lockbit is taken frompreserve_ptrorptr(depending onpreserve_mask).set – whether to set (lock) the bit or unset (unlock). This has no effect, if
lock_bitis set toG_MAXUINT.preserve_mask – if non-zero, a bit-mask for
preserve_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 – if
preserve_maskis non-zero, the bits from this pointer are set in the result.
- Returns:
the mangled pointer.
- pointer_bit_trylock(address: Any, lock_bit: int) bool#
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
addresshas avolatilequalifier, this is a historical artifact and the argument passed to it should not bevolatile.Added in version 2.30.
- Parameters:
address – a pointer to a
gpointer-sized valuelock_bit – a bit value between 0 and 31
- Returns:
Trueif the lock was acquired
- pointer_bit_unlock(address: Any, lock_bit: int) None#
This is equivalent to g_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
addresshas avolatilequalifier, this is a historical artifact and the argument passed to it should not bevolatile.Added in version 2.30.
- Parameters:
address – a pointer to a
gpointer-sized valuelock_bit – a bit value between 0 and 31
- pointer_bit_unlock_and_set(address: Any, lock_bit: int, ptr: Any, 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,ptrmust havelock_bitunset. This also means, you usually can only use this on the lowest bits.Added in version 2.80.
- Parameters:
address – a pointer to a
gpointer-sized valuelock_bit – a bit value between 0 and 31
ptr – the new pointer value to set
preserve_mask – if non-zero, those bits of the current pointer in
addressare preserved. Note that thelock_bitbit will be always set according toset, regardless ofpreserve_maskand the currently set value inaddress.
- poll(fds: PollFD, nfds: int, timeout: int) int#
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 byMainContext, 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
fdsis aPollFDdescribing a single file descriptor to poll. Thefdfield indicates the file descriptor, and theeventsfield indicates the events to poll for. On return, thereventsfields will be filled with the events that actually occurred.On POSIX systems, the file descriptors in
fdscan be any sort of file descriptor, but the situation is much more complicated on Windows. If you need to usepoll()in code that has to run on Windows, the easiest solution is to construct all of yourPollFDwith g_io_channel_win32_make_pollfd().Added in version 2.20.
- Parameters:
fds – file descriptors to poll
nfds – the number of file descriptors in
fdstimeout – amount of time to wait, in milliseconds, or -1 to wait forever
- Returns:
the number of entries in
fdswhosereventsfields were filled in, or 0 if the operation timed out, or -1 on error or if the call was interrupted.
- prefix_error_literal(err: GError | None, prefix: str) GError | None#
Prefixes
prefixto an existing error message. IferrorerrisNone(i.e.: no error variable) then do nothing.Added in version 2.70.
- Parameters:
err – a return location for a
Error, orNoneprefix – string to prefix
errwith
- propagate_error(src: GError) GError | None#
If
destisNone, freesrc; otherwise, movessrcintodest. The error variabledestpoints to must beNone.srcmust be non-None.Note that
srcis no longer valid after this call. If you want to keep using the same GError*, you need to set it toNoneafter calling this function on it.- Parameters:
src – error to move into the return location
- qsort_with_data(pbase: Any, total_elems: int, size: int, compare_func: Callable[[Any, Any, Any], int], user_data: Any = None) None#
This is just like the standard C
`qsort()<man:qsort(3)>`__ function, but the comparison routine accepts a user data argument (like`qsort_r()<man:qsort_r(3)>`__).Unlike
qsort(), this is guaranteed to be a stable sort (since GLib 2.32).Deprecated since version 2.82:
total_elemsis too small to represent larger arrays; usesort_arrayinstead- Parameters:
pbase – start of array to sort
total_elems – elements in the array
size – size of each element
compare_func – function to compare elements
user_data – data to pass to
compare_func
- quark_from_static_string(string: str | None = None) int#
Gets the
Quarkidentifying the given (static) string. If the string does not currently have an associatedQuark, a newQuarkis created, linked to the given string.Note that this function is identical to
quark_from_string()except that if a newQuarkis 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
- Returns:
the
Quarkidentifying the string, or 0 ifstringisNone
- quark_from_string(string: str | None = None) int#
Gets the
Quarkidentifying the given string. If the string does not currently have an associatedQuark, a newQuarkis 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
- Returns:
the
Quarkidentifying the string, or 0 ifstringisNone
- quark_to_string(quark: int) str#
Gets the string associated with the given
Quark.- Parameters:
quark – a
Quark.- Returns:
the string associated with the
Quark
- quark_try_string(string: str | None = None) int#
Gets the
Quarkassociated with the given string, or 0 if string isNoneor it has no associatedQuark.If you want the GQuark to be created if it doesn’t already exist, use
quark_from_string()orquark_from_static_string().This function must not be used before library constructors have finished running.
- Parameters:
string – a string
- Returns:
the
Quarkassociated with the string, or 0 ifstringisNoneor there is noQuarkassociated with it
- random_double() float#
Returns a random
floatequally distributed over the range [0..1).- Returns:
a random number
- random_double_range(begin: float, end: float) float#
Returns a random
floatequally distributed over the range [begin..``end``).- Parameters:
begin – lower closed bound of the interval
end – upper open bound of the interval
- Returns:
a random number
- random_int() int#
Return a random
intequally distributed over the range [0..2^32-1].- Returns:
a random number
- random_int_range(begin: int, end: int) int#
Returns a random
intequally distributed over the range [begin..``end``-1].- Parameters:
begin – lower closed bound of the interval
end – upper open bound of the interval
- Returns:
a random number
- random_set_seed(seed: int) None#
Sets the seed for the global random number generator, which is used by the
g_random_* functions, toseed.- Parameters:
seed – a value to reinitialize the global random number generator
- rc_box_acquire(mem_block: Any) Any#
Acquires a reference on the data pointed by
mem_block.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- Returns:
a pointer to the data, with its reference count increased
- rc_box_alloc(block_size: int) Any#
Allocates
block_sizebytes 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.
Added in version 2.58.
- Parameters:
block_size – the size of the allocation, must be greater than 0
- Returns:
a pointer to the allocated memory
- rc_box_alloc0(block_size: int) Any#
Allocates
block_sizebytes 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.
Added in version 2.58.
- Parameters:
block_size – the size of the allocation, must be greater than 0
- Returns:
a pointer to the allocated memory
- rc_box_dup(block_size: int, mem_block: Any) Any#
Allocates a new block of data with reference counting semantics, and copies
block_sizebytes ofmem_blockinto it.Added in version 2.58.
- Parameters:
block_size – the number of bytes to copy, must be greater than 0
mem_block – the memory to copy
- Returns:
a pointer to the allocated memory
- rc_box_get_size(mem_block: Any) int#
Retrieves the size of the reference counted data pointed by
mem_block.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- Returns:
the size of the data, in bytes
- rc_box_release(mem_block: Any) None#
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.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- rc_box_release_full(mem_block: Any, clear_func: Callable[[Any], None]) None#
Releases a reference on the data pointed by
mem_block.If the reference was the last one, it will call
clear_functo clear the contents ofmem_block, and then will free the resources allocated formem_block.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
clear_func – a function to call when clearing the data
- realloc(mem: Any, n_bytes: int) Any | None#
Reallocates the memory pointed to by
mem, so that it now has space forn_bytesbytes of memory. It returns the new address of the memory, which may have been moved.memmay beNone, in which case it’s considered to have zero-length.n_bytesmay be 0, in which caseNonewill be returned andmemwill be freed unless it isNone.If the allocation fails (because the system is out of memory), the program is terminated.
- Parameters:
mem – the memory to reallocate
n_bytes – new size of the memory in bytes
- Returns:
the new address of the allocated memory
- realloc_n(mem: Any, n_blocks: int, n_block_bytes: int) Any | None#
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.
Added in version 2.24.
- Parameters:
mem – the memory to reallocate
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
- Returns:
the new address of the allocated memory
- regex_match_simple(pattern: str, string: str, compile_options: RegexCompileFlags, match_options: RegexMatchFlags) bool#
- Parameters:
pattern
string
compile_options
match_options
- regex_split_simple(pattern: str, string: str, compile_options: RegexCompileFlags, match_options: RegexMatchFlags) list[str]#
- Parameters:
pattern
string
compile_options
match_options
- reload_user_special_dirs_cache() None#
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.Added in version 2.22.
- remove(filename: str) int#
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().
Added in version 2.6.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
- Returns:
0 if the file was successfully removed, -1 if an error occurred
- rename(oldfilename: str, newfilename: str) 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.
Added in version 2.6.
- Parameters:
oldfilename – a pathname in the GLib file name encoding (UTF-8 on Windows)
newfilename – a pathname in the GLib file name encoding
- Returns:
0 if the renaming succeeded, -1 if an error occurred
- rmdir(filename: str) int#
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.
Added in version 2.6.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
- Returns:
0 if the directory was successfully removed, -1 if an error occurred
- sequence_foreach_range(begin: SequenceIter, end: SequenceIter, func: Callable[[Any, Any], None], user_data: Any = None) None#
- Parameters:
begin
end
func
user_data
- sequence_get(iter: SequenceIter) Any | None#
- Parameters:
iter
- sequence_insert_before(iter: SequenceIter, data: Any = None) SequenceIter#
- Parameters:
iter
data
- sequence_move(src: SequenceIter, dest: SequenceIter) None#
- Parameters:
src
dest
- sequence_move_range(dest: SequenceIter, begin: SequenceIter, end: SequenceIter) None#
- Parameters:
dest
begin
end
- sequence_range_get_midpoint(begin: SequenceIter, end: SequenceIter) SequenceIter#
- Parameters:
begin
end
- sequence_remove(iter: SequenceIter) None#
- Parameters:
iter
- sequence_remove_range(begin: SequenceIter, end: SequenceIter) None#
- Parameters:
begin
end
- sequence_set(iter: SequenceIter, data: Any = None) None#
- Parameters:
iter
data
- sequence_sort_changed(iter: SequenceIter, cmp_func: Callable[[Any, Any, Any], int], cmp_data: Any = None) None#
- Parameters:
iter
cmp_func
cmp_data
- sequence_sort_changed_iter(iter: SequenceIter, iter_cmp: Callable[[SequenceIter, SequenceIter, Any], int], cmp_data: Any = None) None#
- Parameters:
iter
iter_cmp
cmp_data
- sequence_swap(a: SequenceIter, b: SequenceIter) None#
- Parameters:
a
b
- set_application_name(application_name: str) None#
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(), butset_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.
Added in version 2.2.
- Parameters:
application_name – localized name of the application
- set_error_literal(domain: int, code: int, message: str) GError#
Does nothing if
errisNone; iferris non-None, thenerrmust beNone. A newErroris created and assigned toerr. Unlikeset_error(),messageis not a printf()-style format string. Use this function ifmessagecontains text you don’t have control over, that could include printf() escape sequences.Added in version 2.18.
- Parameters:
domain – error domain
code – error code
message – error message
- set_prgname(prgname: str) None#
Sets the name of the program. This name should not be localized, in contrast to
set_application_name().If you are using
GApplicationthe program name is set in g_application_run(). In case of GDK or GTK it is set in gdk_init(), which is called by gtk_init() and theGtkApplication::startup handler. The program name is found by taking the last component ofargv[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.
- Parameters:
prgname – the name of the program.
- set_prgname_once(prgname: str) bool#
If
get_prgname()is not set, this is the same as setting the name viaset_prgname()andTrueis returned. Otherwise, does nothing and returnsFalse. This is thread-safe.- Parameters:
prgname – the name of the program.
- Returns:
whether g_prgname was initialized by the call.
- setenv(variable: str, value: str, 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 withenviron_setenv()andenviron_unsetenv(), and then pass that array directly to execvpe(),spawn_async(), or the like.Added in version 2.4.
- 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.
- Returns:
Falseif the environment variable couldn’t be set.
- shell_parse_argv(command_line: str) 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_lineis an empty string (or a string containing only whitespace),EMPTY_STRINGwill be returned. It’s guaranteed thatargvpwill be a non-empty array if this function returns successfully.Free the returned vector with
strfreev().- Parameters:
command_line – command line to parse
- Returns:
Trueon success,Falseif error set
- shell_quote(unquoted_string: str) str#
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
- Returns:
quoted string
- shell_unquote(quoted_string: str) str#
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 returnsNoneand sets the error.The
quoted_stringneed 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
- Returns:
an unquoted string
- slice_alloc(block_size: int) Any | None#
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.
Added in version 2.10.
- Parameters:
block_size – the number of bytes to allocate
- Returns:
a pointer to the allocated memory block, which will be
Noneif and only ifmem_sizeis 0
- slice_alloc0(block_size: int) Any | None#
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.
Added in version 2.10.
- Parameters:
block_size – the number of bytes to allocate
- Returns:
a pointer to the allocated block, which will be
Noneif and only ifmem_sizeis 0
- slice_free1(block_size: int, mem_block: Any = None) None#
Frees a block of memory.
The memory must have been allocated via
slice_alloc()orslice_alloc0()and theblock_sizehas to match the size specified upon allocation. Note that the exact release behaviour can be changed with the [G_DEBUG=gc-friendly][G_DEBUG] environment variable.If
mem_blockisNone, this function does nothing.Since GLib 2.76 this always uses the system free_sized() implementation internally.
Added in version 2.10.
- Parameters:
block_size – the size of the block
mem_block – a pointer to the block to free
- slice_free_chain_with_offset(block_size: int, mem_chain: Any, next_offset: int) None#
Frees a linked list of memory blocks of structure type
type.The memory blocks must be equal-sized, allocated via
slice_alloc()orslice_alloc0()and linked together by anextpointer (similar toGSList). The offset of thenextfield in each block is passed as third argument. Note that the exact release behaviour can be changed with the [G_DEBUG=gc-friendly][G_DEBUG] environment variable.If
mem_chainisNone, this function does nothing.Since GLib 2.76 this always uses the system free_sized() implementation internally.
Added in version 2.10.
- Parameters:
block_size – the size of the blocks
mem_chain – a pointer to the first block of the chain
next_offset – the offset of the
nextfield in the blocks
- slice_get_config(ckey: SliceConfig) int#
- Parameters:
ckey
- slice_get_config_state(ckey: SliceConfig, address: int, n_values: int) int#
- Parameters:
ckey
address
n_values
- slice_set_config(ckey: SliceConfig, value: int) None#
- Parameters:
ckey
value
- source_remove_by_funcs_user_data(funcs: SourceFuncs, user_data: Any = None) bool#
- Parameters:
funcs
user_data
- spaced_primes_closest(num: int) int#
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 aHashTable.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
int- Returns:
the smallest prime number from a built-in array of primes which is larger than
num
- spawn_async(argv: ~typing.Sequence[str], envp: ~typing.Sequence[str] | None = None, working_directory: str | None = None, flags: ~gi.repository.GLib.SpawnFlags = <SpawnFlags.DEFAULT: 0>, child_setup: ~typing.Callable[[~typing.Any], None] | None = None, user_data: ~typing.Any = None, standard_input: bool = False, standard_output: bool = False, standard_error: bool = False) tuple[Pid, int | None, int | None, int | None]#
- spawn_async(argv, envp=None, working_directory=None,
flags=0, child_setup=None, user_data=None, standard_input=None, standard_output=None, standard_error=None) -> (pid, stdin, stdout, stderr)
Execute a child program asynchronously within a glib.MainLoop() See the reference manual for a complete reference.
- Parameters:
argv – child’s argument vector
envp – child’s environment, or
Noneto inherit parent’sworking_directory – child’s current working directory, or
Noneto inherit parent’sflags – flags from
SpawnFlagschild_setup – function to run in the child just before
exec()user_data – user data for
child_setupstandard_input
standard_output
standard_error
- Returns:
Trueon success,Falseif error is set
- spawn_async_with_fds(working_directory: str | None, argv: list[str], envp: list[str] | None, flags: SpawnFlags, child_setup: Callable[[Any], None] | None, user_data: Any, stdin_fd: int, stdout_fd: int, stderr_fd: int) tuple[bool, int]#
Executes a child program asynchronously.
Identical to
spawn_async_with_pipes_and_fds()but withn_fdsset to zero, so no FD assignments are used.Added in version 2.58.
- Parameters:
working_directory – child’s current working directory, or
Noneto inherit parent’s, in the GLib file name encodingargv – child’s argument vector, in the GLib file name encoding; it must be non-empty and
None-terminatedenvp – child’s environment, or
Noneto inherit parent’s, in the GLib file name encodingflags – flags from
SpawnFlagschild_setup – function to run in the child just before
exec()user_data – user data for
child_setupstdin_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
- Returns:
Trueon success,Falseif an error was set
- spawn_async_with_pipes(working_directory: str | None, argv: list[str], envp: list[str] | None, flags: SpawnFlags, child_setup: Callable[[Any], None] | None = None, user_data: Any = None) tuple[bool, int, int, int, int]#
Identical to
spawn_async_with_pipes_and_fds()but withn_fdsset to zero, so no FD assignments are used.- Parameters:
working_directory – child’s current working directory, or
Noneto inherit parent’s, in the GLib file name encodingargv – child’s argument vector, in the GLib file name encoding; it must be non-empty and
None-terminatedenvp – child’s environment, or
Noneto inherit parent’s, in the GLib file name encodingflags – flags from
SpawnFlagschild_setup – function to run in the child just before
exec()user_data – user data for
child_setup
- Returns:
Trueon success,Falseif an error was set
- spawn_async_with_pipes_and_fds(working_directory: str | None, argv: list[str], envp: list[str] | None, flags: SpawnFlags, child_setup: Callable[[Any], None] | None, user_data: Any, stdin_fd: int, stdout_fd: int, stderr_fd: int, source_fds: list[int] | None = None, target_fds: list[int] | None = None) tuple[bool, int, 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.argvshould be aNone-terminated array of strings, to be passed as the argument vector for the child. The first string inargvis of course the name of the program to execute. By default, the name of the program must be a full path. Ifflagscontains theSEARCH_PATHflag, thePATHenvironment variable is used to search for the executable. Ifflagscontains theSEARCH_PATH_FROM_ENVPflag, thePATHvariable fromenvpis used to search for the executable. If both theSEARCH_PATHandSEARCH_PATH_FROM_ENVPflags are set, thePATHvariable fromenvptakes precedence over the environment variable.If the program name is not a full path and
SEARCH_PATHflag is not used, then the program will be run from the current directory (orworking_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 awmain()instead ofmain().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’sspawn*()family of functions (whichspawn_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 tomain(). Complications arise when you have argument vector elements that contain spaces or double quotes. Thespawn*()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 runtimespawn()function.The returned
child_pidon Windows is a handle to the child process, not its identifier. Process handles and process identifiers are different concepts on Windows.envpis aNone-terminated array of strings, where each string has the formKEY=VALUE. This will become the child’s environment. IfenvpisNone, the child inherits its parent’s environment.flagsshould be the bitwise OR of any flags you want to affect the function’s behaviour. TheDO_NOT_REAP_CHILDmeans that the child will not automatically be reaped; you must use a child watch (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 callspawn_close_pid()on thechild_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 theSIGCHLDsignal manually. On Windows, callingspawn_close_pid()is equivalent to callingCloseHandle()on the process handle returned inchild_pid). Seechild_watch_add().Open UNIX file descriptors marked as
FD_CLOEXECwill be automatically closed in the child process.LEAVE_DESCRIPTORS_OPENmeans that other open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before callingexec()in the child.SEARCH_PATHmeans thatargv[0] need not be an absolute path, it will be looked for in thePATHenvironment variable.SEARCH_PATH_FROM_ENVPmeans need not be an absolute path, it will be looked for in thePATHvariable fromenvp. If bothSEARCH_PATHandSEARCH_PATH_FROM_ENVPare used, the value fromenvptakes precedence over the environment.CHILD_INHERITS_STDINmeans that the child will inherit the parent’s standard input (by default, the child’s standard input is attached to/dev/null).STDIN_FROM_DEV_NULLexplicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, thestdin_pipe_outargument is ignored.STDOUT_TO_DEV_NULLmeans that the child’s standard output will be discarded (by default, it goes to the same location as the parent’s standard output).CHILD_INHERITS_STDOUTexplicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, thestdout_pipe_outargument is ignored.STDERR_TO_DEV_NULLmeans that the child’s standard error will be discarded (by default, it goes to the same location as the parent’s standard error).CHILD_INHERITS_STDERRexplicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, thestderr_pipe_outargument is ignored.It is valid to pass the same FD in multiple parameters (e.g. you can pass a single FD for both
stdout_fdandstderr_fd, and include it insource_fdstoo).source_fdsandtarget_fdsallow zero or more FDs from this process to be remapped to different FDs in the spawned process. Ifn_fdsis greater than zero,source_fdsandtarget_fdsmust both be non-Noneand the same length. Each FD insource_fdsis remapped to the FD number at the same index intarget_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 equalstdin_fd,stdout_fdorstderr_fdwill overwrite them in the spawned process.source_fdsis supported on Windows since 2.72.FILE_AND_ARGV_ZEROmeans that 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_pipes()usesargv[0] as the file to execute, and passes all ofargvto the child.child_setupanduser_dataare 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 callingexec(). That is,child_setupis called just before callingexec()in the child. Obviously actions taken in this function will only affect the child, not the parent.On Windows, there is no separate
fork()andexec()functionality. Child processes are created and run with a single API call,CreateProcess(). There is no sensible thingchild_setupcould be used for on Windows so it is ignored and not called.If non-
None,child_pidwill on Unix be filled with the child’s process ID. You can use the process ID to send signals to the child, or to usechild_watch_add()(orwaitpid()) if you specified theDO_NOT_REAP_CHILDflag. On Windows,child_pidwill be filled with a handle to the child process only if you specified theDO_NOT_REAP_CHILDflag. You can then access the child process using the Win32 API, for example wait for its termination with theWaitFor*()functions, or examine its exit code withGetExitCodeProcess(). You should close the handle withCloseHandle()orspawn_close_pid()when you no longer need it.If non-
None, thestdin_pipe_out,stdout_pipe_out,stderr_pipe_outlocations 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 ofspawn_async_with_pipes()must close these file descriptors when they are no longer in use. If these parameters areNone, the corresponding pipe won’t be created.If
stdin_pipe_outisNone, the child’s standard input is attached to/dev/nullunlessCHILD_INHERITS_STDINis set.If
stderr_pipe_outis NULL, the child’s standard error goes to the same location as the parent’s standard error unlessSTDERR_TO_DEV_NULLis set.If
stdout_pipe_outis NULL, the child’s standard output goes to the same location as the parent’s standard output unlessSTDOUT_TO_DEV_NULLis set.errorcan beNoneto ignore errors, or non-Noneto report errors. If an error is set, the function returnsFalse. Errors are reported even if they occur in the child (for example if the executable in@argv[0]is not found). Typically themessagefield 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, andstderr_pipe_outwill not be filled with valid values.If
child_pidis notNoneand an error does not occur then the returned process reference must be closed usingspawn_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:DO_NOT_REAP_CHILDis setLEAVE_DESCRIPTORS_OPENis setSEARCH_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
GdkAppLaunchContext,GAppLaunchContext, or set theDISPLAYenvironment variable.Added in version 2.68.
- Parameters:
working_directory – child’s current working directory, or
Noneto inherit parent’s, in the GLib file name encodingargv – child’s argument vector, in the GLib file name encoding; it must be non-empty and
None-terminatedenvp – child’s environment, or
Noneto inherit parent’s, in the GLib file name encodingflags – flags from
SpawnFlagschild_setup – function to run in the child just before
exec()user_data – user data for
child_setupstdin_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 process
target_fds – array of FDs to remap
source_fdsto in the child process
- Returns:
Trueon success,Falseif an error was set
- spawn_check_exit_status(wait_status: int) bool#
An old name for
spawn_check_wait_status(), deprecated because its name is misleading.Despite the name of the function,
wait_statusmust be the wait status as returned byspawn_sync(), g_subprocess_get_status(),waitpid(), etc. On Unix platforms, it is incorrect for it to be the exit status as passed toexit()or returned by g_subprocess_get_exit_status() orWEXITSTATUS().Added in version 2.34.
Deprecated since version 2.70: Use
spawn_check_wait_status()instead, and check whether your code is conflating wait and exit statuses.- Parameters:
wait_status – A status as returned from
spawn_sync()- Returns:
Trueif child exited successfully,Falseotherwise (anderrorwill be set)
- spawn_check_wait_status(wait_status: int) bool#
Set
errorifwait_statusindicates the child exited abnormally (e.g. with a nonzero exit code, or via a fatal signal).The
spawn_sync()andchild_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_statusrequired 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
Erroror print a message to standard error. In that common case, this function can be used. Note that the error message inerrorwill contain human-readable information about the wait status.The
domainandcodeoferrorhave 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 ofwait_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
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_statusdirectly. 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.Added in version 2.70.
- Parameters:
wait_status – A platform-specific wait status as returned from
spawn_sync()- Returns:
Trueif child exited successfully,Falseotherwise (anderrorwill be set)
- spawn_close_pid(pid: int) None#
On some platforms, notably Windows, the
Pidtype 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(command_line: str) bool#
A simple version of
spawn_async()that parses a command line withshell_parse_argv()and passes it tospawn_async().Runs a command line in the background. Unlike
spawn_async(), theSEARCH_PATHflag is enabled, other flags are not. Note thatSEARCH_PATHcan have security implications, so consider usingspawn_async()directly if appropriate. Possible errors are those fromshell_parse_argv()andspawn_async().The same concerns on Windows apply as for
spawn_command_line_sync().- Parameters:
command_line – a command line
- Returns:
Trueon success,Falseif error is set
- spawn_command_line_sync(command_line: str) 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_lineargument will be parsed byshell_parse_argv().Unlike
spawn_sync(), theSEARCH_PATHflag is enabled. Note thatSEARCH_PATHcan have security implications, so consider usingspawn_sync()directly if appropriate.Possible errors are those from
spawn_sync()and those fromshell_parse_argv().If
wait_statusis non-None, the platform-specific status of the child is stored there; see the documentation ofspawn_check_wait_status()for how to use and interpret this. On Unix platforms, note that it is usually not equal to the integer passed toexit()or returned frommain().On Windows, please note the implications of
shell_parse_argv()parsingcommand_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 acommand_linecontaining canonical Windows paths, like “c:program filesappapp.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 filesappapp.exe’ ‘e:folderargument.txt’”.- Parameters:
command_line – a command line
- Returns:
Trueon success,Falseif an error was set
- spawn_sync(working_directory: str | None, argv: list[str], envp: list[str] | None, flags: SpawnFlags, child_setup: Callable[[Any], None] | None = None, user_data: Any = 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_outputandstandard_error, if those parameters are non-None. Note that you must set theSTDOUT_TO_DEV_NULLandSTDERR_TO_DEV_NULLflags when passingNoneforstandard_outputandstandard_error.If
wait_statusis non-None, the platform-specific status of the child is stored there; see the documentation ofspawn_check_wait_status()for how to use and interpret this. On Unix platforms, note that it is usually not equal to the integer passed toexit()or returned frommain().Note that it is invalid to pass
DO_NOT_REAP_CHILDinflags, and on POSIX platforms, the same restrictions as forchild_watch_source_new()apply.If an error occurs, no data is returned in
standard_output,standard_error, orwait_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, or
Noneto inherit parent’sargv – child’s argument vector, which must be non-empty and
None-terminatedenvp – child’s environment, or
Noneto inherit parent’sflags – flags from
SpawnFlagschild_setup – function to run in the child just before
exec()user_data – user data for
child_setup
- Returns:
Trueon success,Falseif an error was set
- stat(filename: str, buf: StatBuf) int#
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_modefield 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
StatBufwhich 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().
Added in version 2.6.
- 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
- Returns:
0 if the information was successfully retrieved, -1 if an error occurred
- stpcpy(dest: str, src: str) str#
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 buffer
src – source string
- Returns:
a pointer to the trailing nul byte in
dest
- str_equal(v1: Any, v2: Any) bool#
Compares two strings for byte-by-byte equality and returns
Trueif they are equal. It can be passed tonew()as thekey_equal_funcparameter, when using non-Nonestrings as keys in aHashTable.This function is typically used for hash table comparisons, but can be used for general purpose comparisons of non-
Nonestrings. For aNone-safe string comparison function, seestrcmp0().- Parameters:
v1 – a key
v2 – a key to compare with
v1
- Returns:
Trueif the two keys match
- str_has_prefix(str: str, prefix: str) bool#
Looks whether the string
strbegins withprefix.Added in version 2.2.
- Parameters:
str – a string to look in
prefix – the prefix to look for
- Returns:
true if
strbegins withprefix, false otherwise
- str_has_suffix(str: str, suffix: str) bool#
Looks whether a string ends with
suffix.Added in version 2.2.
- Parameters:
str – a string to look in
suffix – the suffix to look for
- Returns:
true if
strends withsuffix, false otherwise
- str_hash(v: Any) int#
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
new()as thehash_funcparameter, when using non-Nonestrings as keys in aHashTable.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
- Returns:
a hash value corresponding to the key
- str_is_ascii(str: str) bool#
Determines if a string is pure ASCII. A string is pure ASCII if it contains no bytes with the high bit set.
Added in version 2.40.
- Parameters:
str – a string
- Returns:
true if
stris ASCII
- str_match_string(search_term: str, potential_hit: str, accept_alternates: bool) bool#
Checks if a search conducted for
search_termshould matchpotential_hit.This function calls
str_tokenize_and_foldon bothsearch_termandpotential_hit. ASCII alternates are never taken forsearch_termbut will be taken forpotential_hitaccording to the value ofaccept_alternates.A hit occurs when each folded token in
search_termis a prefix of a folded token frompotential_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 callg_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).
Added in version 2.40.
- Parameters:
search_term – the search term from the user
potential_hit – the text that may be a hit
accept_alternates – if true, ASCII alternates are accepted
- Returns:
true if
potential_hitis a hit
- str_to_ascii(str: str, from_locale: str | None = None) str#
Transliterate
strto plain ASCII.For best results,
strshould 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
stris known, it can used to improve the accuracy of the translation by passing it asfrom_locale. It should be a valid POSIX locale string (of the formlanguage[_territory][.codeset][@modifier]).If
from_localeisNonethen 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"forfrom_locale.Added in version 2.40.
- Parameters:
str – a string, in UTF-8
from_locale – the source locale, if known
- Returns:
a string in plain ASCII
- str_tokenize_and_fold(string: str, translit_locale: str | None = None) tuple[list[str], list[str]]#
Tokenizes
stringand 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_isalnumorunichar_ismark.Each token is then (Unicode) normalised and case-folded. If
ascii_alternatesis non-NULLand 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.Added in version 2.40.
- Parameters:
string – a string to tokenize
translit_locale – the language code (like ‘de’ or ‘en_GB’) from which
stringoriginates
- Returns:
the folded tokens
- strcanon(string: str, valid_chars: str, substitutor: int) str#
For each character in
string, if the character is not invalid_chars, replaces the character withsubstitutor.Modifies
stringin place, and returnstringitself, not a copy. The return value is to allow nesting such as:g_ascii_strup (g_strcanon (str, "abc", '?'))
In order to modify a copy, you may use
strdup:reformatted = g_strcanon (g_strdup (const_str), "abc", '?'); … g_free (reformatted);
- Parameters:
string – a nul-terminated array of bytes
valid_chars – bytes permitted in
stringsubstitutor – replacement character for disallowed bytes
- Returns:
the modified
string
- strcasecmp(s1: str, s2: str) int#
A case-insensitive string comparison, corresponding to the standard
strcasecmp()function on platforms which support it.Deprecated since version 2.2: See
strncasecmpfor a discussion of why this function is deprecated and how to replace it.- Parameters:
s1 – string to compare with
s2s2 – string to compare with
s1
- Returns:
0 if the strings match, a negative value if
s1<s2, or a positive value ifs1>s2
- strchomp(string: str) str#
Removes trailing whitespace from a string.
This function doesn’t allocate or reallocate any memory; it modifies
stringin place. Therefore, it cannot be used on statically allocated strings.The pointer to
stringis returned to allow the nesting of functions.Also see
strchugandstrstrip.- Parameters:
string – a string to remove the trailing whitespace from
- Returns:
the modified
string
- strchug(string: str) str#
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
stringin place. Therefore, it cannot be used on statically allocated strings.The pointer to
stringis returned to allow the nesting of functions.Also see
strchompandstrstrip.- Parameters:
string – a string to remove the leading whitespace from
- Returns:
the modified
string
- strcmp0(str1: str | None = None, str2: str | None = None) int#
Compares
str1andstr2like strcmp(). HandlesNonegracefully by sorting it before non-Nonestrings. Comparing twoNonepointers returns 0.Added in version 2.16.
- Parameters:
str1 – a C string or
Nonestr2 – another C string or
None
- Returns:
an integer less than, equal to, or greater than zero, if
str1is <, == or > thanstr2.
- strcompress(source: str) str#
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\followed by one to three octal digits → the numeric value (mod 255)\followed by any other character → the character as is. For example,\\will turn into a backslash (\) and\"into a double quote (").
strescapedoes the reverse conversion.- Parameters:
source – a string to compress
- Returns:
a newly-allocated copy of
sourcewith all escaped character compressed
- strdelimit(string: str, delimiters: str | None, new_delimiter: int) str#
Converts any delimiter characters in
stringtonew_delimiter.Any characters in
stringwhich are found indelimitersare changed to thenew_delimitercharacter. Modifiesstringin place, and returnsstringitself, not a copy.The return value is to allow nesting such as:
g_ascii_strup (g_strdelimit (str, "abc", '?'))
In order to modify a copy, you may use
strdup:reformatted = g_strdelimit (g_strdup (const_str), "abc", '?'); … g_free (reformatted);
- Parameters:
string – the string to convert
delimiters – a string containing the current delimiters, or
NULLto use the standard delimiters defined inSTR_DELIMITERSnew_delimiter – the new delimiter character
- Returns:
the modified
string
- strdown(string: str) str#
Converts a string to lower case.
Deprecated since version 2.2: This function is totally broken for the reasons discussed in the
strncasecmpdocs — useascii_strdownorutf8_strdowninstead.- Parameters:
string – the string to convert
- Returns:
the string
- strdup(str: str | None = None) str#
Duplicates a string. If
strisNULLit returnsNULL.- Parameters:
str – the string to duplicate
- Returns:
a newly-allocated copy of
str
- strdupv(str_array: list[str] | None = None) list[str] | None#
Copies an array of strings. The copy is a deep copy; each string is also copied.
If called on a
NULLvalue,g_strdupv()simply returnsNULL.- Parameters:
str_array – an array of strings to copy
- Returns:
a newly-allocated array of strings. Use
strfreevto free it.
- strerror(errnum: int) str#
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
errnowill 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:int saved_errno; ret = read (blah); saved_errno = errno; g_strerror (saved_errno);
- Parameters:
errnum – the system error number. See the standard C
errnodocumentation- Returns:
the string describing the error code
- strescape(source: str, exceptions: str | None = None) str#
It replaces the following special characters in the string
sourcewith their corresponding C escape sequence:Symbol | Escape —|—
U+0008 Backspace |
\bU+000C Form Feed |\fU+000A Line Feed |\nU+000D Carriage Return |\rU+0009 Horizontal Tabulation |\tU+000B Vertical Tabulation |\vIt 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 inexceptionsare not escaped.strcompressdoes the reverse conversion.- Parameters:
source – a string to escape
exceptions – a string of characters not to escape in
source
- Returns:
a newly-allocated copy of
sourcewith special characters escaped
- strfreev(str_array: list[str] | None = None) None#
Frees an array of strings, as well as each string it contains.
If
str_arrayisNULL, this function simply returns.- Parameters:
str_array – an array of strings to free
- strip_context(msgid: str, msgval: str) str#
An auxiliary function for gettext() support (see Q_()).
Added in version 2.4.
- Parameters:
msgid – a string
msgval – another string
- Returns:
msgval, unlessmsgvalis identical tomsgidand contains a ‘|’ character, in which case a pointer to the substring of msgid after the first ‘|’ character is returned.
- strjoinv(separator: str | None, str_array: list[str]) str#
Joins an array of strings together to form one long string, with the optional
separatorinserted between each of them.If
str_arrayhas no items, the return value will be an empty string. Ifstr_arraycontains a single item,separatorwill not appear in the resulting string.- Parameters:
separator – a string to insert between each of the strings
str_array – an array of strings to join
- Returns:
a newly-allocated string containing all of the strings joined together, with
separatorbetween them
- strlcat(dest: str, src: str, dest_size: int) int#
Portability wrapper that calls
strlcat()on systems which have it, and emulates it otherwise. Appends nul-terminatedsrcstring todest, guaranteeing nul-termination fordest. The total size ofdestwon’t exceeddest_size.At most
dest_size- 1 characters will be copied. Unlikestrncat(),dest_sizeis the full size of dest, not the space left over. This function does not allocate memory. It always nul-terminates (unlessdest_size== 0 or there were no nul characters in thedest_sizecharacters of dest to start with).Caveat: this is supposedly a more secure alternative to
strcat()orstrncat(), but for real securitystrconcatis harder to mess up.- Parameters:
dest – destination buffer, already containing one nul-terminated string
src – source buffer
dest_size – length of
destbuffer in bytes (not length of existing string insidedest)
- Returns:
size of attempted result, which is
MIN (dest_size, strlen (original dest)) + strlen (src), so ifretval>=dest_size, truncation occurred
- strlcpy(dest: str, src: str, dest_size: int) int#
Portability wrapper that calls
strlcpy()on systems which have it, and emulatesstrlcpy()otherwise. Copiessrctodest;destis guaranteed to be nul-terminated;srcmust be nul-terminated;dest_sizeis the buffer size, not the number of bytes to copy.At most
dest_size- 1 characters will be copied. Always nul-terminates (unlessdest_sizeis 0). This function does not allocate memory. Unlikestrncpy(), this function doesn’t paddest(so it’s often faster). It returns the size of the attempted result,strlen (src), so ifretval>=dest_size, truncation occurred.Caveat:
strlcpy()is supposedly more secure thanstrcpy()orstrncpy(), but if you really want to avoid screwups,strdupis an even better idea.- Parameters:
dest – destination buffer
src – source buffer
dest_size – length of
destin bytes
- Returns:
length of
src
- strncasecmp(s1: str, s2: str, n: int) int#
A case-insensitive string comparison, corresponding to the standard
strncasecmp()function on platforms which support it. It is similar tostrcasecmpexcept it only compares the firstncharacters of the strings.Deprecated since version 2.2: The problem with
g_strncasecmp()is that it does the comparison by callingtoupper()/tolower(). These functions are locale-specific and operate on single bytes. However, it is impossible to handle things correctly from an internationalization standpoint by operating on bytes, since characters may be multibyte. Thusg_strncasecmp()is broken if your string is guaranteed to be ASCII, since it is locale-sensitive, and it’s broken if your string is localized, since it doesn’t work on many encodings at all, including UTF-8, EUC-JP, etc.- There are therefore two replacement techniques:
ascii_strncasecmp, which only works on ASCII and is not locale-sensitive, and
utf8_casefoldfollowed bystrcmp()on the resulting strings, which is good for case-insensitive sorting of UTF-8.
- Parameters:
s1 – string to compare with
s2s2 – string to compare with
s1n – the maximum number of characters to compare
- Returns:
0 if the strings match, a negative value if
s1<s2, or a positive value ifs1>s2
- There are therefore two replacement techniques:
- strndup(str: str | None, n: int) str | None#
Duplicates the first
nbytes of a string, returning a newly-allocated buffern+ 1 bytes long which will always be nul-terminated. Ifstris less thannbytes long the buffer is padded with nuls. IfstrisNULLit returnsNULL.To copy a number of characters from a UTF-8 encoded string, use
utf8_strncpyinstead.- Parameters:
str – the string to duplicate
n – the maximum number of bytes to copy from
str
- Returns:
a newly-allocated buffer containing the first
nbytes ofstr
- strnfill(length: int, fill_char: int) str#
Creates a new string
lengthbytes long filled withfill_char.- Parameters:
length – the length of the new string
fill_char – the byte to fill the string with
- Returns:
a newly-allocated string filled with
fill_char
- strreverse(string: str) str#
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, useutf8_strreverse.- Parameters:
string – the string to reverse
- Returns:
the
string, reversed in place
- strrstr(haystack: str, needle: str) str | None#
Searches the string
haystackfor the last occurrence of the stringneedle.The fact that this function returns
gchar *rather thanconst gchar *is a historical artifact.- Parameters:
haystack – a string to search in
needle – the string to search for
- Returns:
a pointer to the found occurrence, or
NULLif not found
- strrstr_len(haystack: str, haystack_len: int, needle: str) str | None#
Searches the string
haystackfor the last occurrence of the stringneedle, limiting the length of the search tohaystack_len.The fact that this function returns
gchar *rather thanconst gchar *is a historical artifact.- Parameters:
haystack – a string to search in
haystack_len – the maximum length of
haystackin bytes. A length of-1can be used to mean “search the entire string”, likestrrstrneedle – the string to search for
- Returns:
a pointer to the found occurrence, or
NULLif not found
- strsignal(signum: int) str#
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 thestrsignal()function.- Parameters:
signum – the signal number. See the
signaldocumentation- Returns:
the string describing the signal
- strsplit(string: str, delimiter: str, max_tokens: int) list[str]#
Splits a string into a maximum of
max_tokenspieces, using the givendelimiter. Ifmax_tokensis reached, the remainder ofstringis 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 split
delimiter – a string which specifies the places at which to split the string. The delimiter is not included in any of the resulting strings, unless
max_tokensis reached.max_tokens – the maximum number of pieces to split
stringinto If this is less than 1, the string is split completely
- Returns:
a newly-allocated array of strings, freed with
strfreev
- strsplit_set(string: str, delimiters: str, max_tokens: int) list[str]#
Splits
stringinto a number of tokens not containing any of the characters indelimiters. A token is the (possibly empty) longest string that does not contain any of the characters indelimiters. Ifmax_tokensis 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:”, “:/”, -1) is an array containing the four strings “”, “def”, “ghi”, 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_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.
Added in version 2.4.
- Parameters:
string – a string to split
delimiters – a string containing characters that are used to split the string. Can be empty, which will result in no string splitting
max_tokens – the maximum number of tokens to split
stringinto. If this is less than 1, the string is split completely
- Returns:
a newly-allocated array of strings. Use
strfreevto free it.
- strstr_len(haystack: str, haystack_len: int, needle: str) str | None#
Searches the string
haystackfor the first occurrence of the stringneedle, limiting the length of the search tohaystack_lenor a nul terminator byte (whichever is reached first).A length of
-1can be used to mean “search the entire string”, likestrstr().The fact that this function returns
gchar *rather thanconst gchar *is a historical artifact.- Parameters:
haystack – a string to search in
haystack_len – the maximum length of
haystackin bytes, or-1to search it entirelyneedle – the string to search for
- Returns:
a pointer to the found occurrence, or
NULLif not found
- strtod(nptr: str) tuple[float, str]#
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 withascii_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
- Returns:
the converted value
- strup(string: str) str#
Converts a string to upper case.
Deprecated since version 2.2: This function is totally broken for the reasons discussed in the
strncasecmpdocs — useascii_struporutf8_strupinstead.- Parameters:
string – the string to convert
- Returns:
the string
- strv_contains(strv: list[str], str: str) bool#
Checks if an array of strings contains the string
straccording tostr_equal.strvmust not beNULL.Added in version 2.44.
- Parameters:
strv – an array of strings to search in
str – the string to search for
- Returns:
true if
stris an element ofstrv
- strv_equal(strv1: list[str], strv2: list[str]) bool#
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 (usingqsort_with_dataor similar).Elements are compared using
str_equal. To match independently of order, sort the arrays first (usingqsort_with_dataor similar).Two empty arrays are considered equal. Neither
strv1norstrv2may beNULL.Added in version 2.60.
- Parameters:
strv1 – an array of strings to compare to
strv2strv2 – an array of strings to compare to
strv1
- Returns:
true if
strv1andstrv2are equal
- strv_get_type() GType#
- strv_length(str_array: list[str]) int#
Returns the length of an array of strings.
str_arraymust not beNULL.Added in version 2.6.
- Parameters:
str_array – an array of strings
- Returns:
length of
str_array
- test_add_data_func(testpath: str, test_data: Any, test_func: Callable[[Any], None]) None#
Create a new test case, similar to
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 slash-separated portions oftestpath. Thetest_dataargument will be passed as first argument totest_func.If
testpathincludes the component “subprocess” anywhere in it, the test will be skipped by default, and only run if explicitly required via the-pcommand-line option ortest_trap_subprocess().No component of
testpathmay start with a dot (.) if theTEST_OPTION_ISOLATE_DIRSoption is being used; and it is recommended to do so even if it isn’t.Added in version 2.16.
- Parameters:
testpath – /-separated test case path name for the test.
test_data – Test data argument for the test function.
test_func – The test function to invoke for this test.
- test_add_data_func_full(testpath: str, test_data: Any, test_func: Callable[[Any], None]) None#
Create a new test case, as with
test_add_data_func(), but freeingtest_dataafter the test run is complete.Added in version 2.34.
- Parameters:
testpath – /-separated test case path name for the test.
test_data – Test data argument for the test function.
test_func – The test function to invoke for this test.
- test_add_func(testpath: str, test_func: Callable[[], None]) None#
Create a new test case, similar to
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 slash-separated portions oftestpath.If
testpathincludes the component “subprocess” anywhere in it, the test will be skipped by default, and only run if explicitly required via the-pcommand-line option ortest_trap_subprocess().No component of
testpathmay start with a dot (.) if theTEST_OPTION_ISOLATE_DIRSoption is being used; and it is recommended to do so even if it isn’t.Added in version 2.16.
- Parameters:
testpath – /-separated test case path name for the test.
test_func – The test function to invoke for this test.
- test_assert_expected_messages_internal(domain: str, file: str, line: int, func: str) None#
- Parameters:
domain
file
line
func
- test_bug(bug_uri_snippet: str) None#
This function 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()andbug_uri_snippet. Iftest_bug_base()has not been called, it is assumed to be the empty string, so a full URI can be provided totest_bug()instead.Since GLib 2.70, the base URI is not prepended to
bug_uri_snippetif it is already a valid URI.Added in version 2.16.
- Parameters:
bug_uri_snippet – Bug specific bug tracker URI or URI portion.
- test_bug_base(uri_pattern: str) None#
Specify the base URI for bug reports.
The base URI is used to construct bug report messages for
test_message()whentest_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 touri_pattern, or by replacing the special string%swithinuri_patternif that is present.If
test_bug_base()is not called, bug URIs are formed solely from the value provided bytest_bug().Added in version 2.16.
- Parameters:
uri_pattern – the base pattern for bug URIs
- test_disable_crash_reporting() None#
Attempt 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.
Added in version 2.78.
- test_expect_message(log_domain: str | None, log_level: LogLevelFlags, pattern: str) None#
Indicates that a message with the given
log_domainandlog_level, with text matchingpattern, 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 (
logwithoutG_LOG_USE_STRUCTUREDdefined). It will not work with the structured logging API. See Testing for Messages.Use
test_assert_expected_messagesto 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
errormessages, sinceerrorintentionally never returns even if the program doesn’t abort; usetest_trap_subprocessin this case.If messages at
LEVEL_DEBUGare emitted, but not explicitly expected viatest_expect_messagethen they will be ignored.Added in version 2.34.
- Parameters:
log_domain – the log domain of the message
log_level – the log level of the message
pattern – a glob-style pattern (see
PatternSpec)
- test_fail() None#
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()andtest_incomplete(), this function does not log a message alongside the test failure. If details of the test failure are available, either log them withtest_message()beforetest_fail(), or usetest_fail_printf()instead.Added in version 2.30.
- test_failed() bool#
Returns whether a test has already failed. This will be the case when
test_fail(),test_incomplete()ortest_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.
Added in version 2.38.
- Returns:
Trueif the test has failed
- test_get_dir(file_type: TestFileType) str#
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.
Added in version 2.38.
- Parameters:
file_type – the type of file (built vs. distributed)
- Returns:
the path of the directory, owned by GLib
- test_get_path() str#
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.
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.
Added in version 2.68.
- Returns:
the test path for the test currently being run
- test_incomplete(msg: str | None = None) None#
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.
Added in version 2.38.
- Parameters:
msg – explanation
- test_log_type_name(log_type: TestLogType) str#
- Parameters:
log_type
- test_queue_destroy(destroy_func: Callable[[Any], None], destroy_data: Any = None) None#
Enqueues a callback
destroy_functo 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
Abefore callbackBwill causeB()to be called beforeA()during teardown.Added in version 2.16.
- Parameters:
destroy_func – Destroy callback for teardown phase.
destroy_data – Destroy callback data.
- test_queue_free(gfree_pointer: Any = None) None#
Enqueue a pointer to be released with
free()during the next teardown phase. This is equivalent to callingtest_queue_destroy()with a destroy callback offree().Added in version 2.16.
- Parameters:
gfree_pointer – the pointer to be stored.
- test_rand_double() float#
Get a reproducible random floating point number, see
test_rand_int()for details on test case random numbers.Added in version 2.16.
- Returns:
a random number from the seeded random number generator.
- test_rand_double_range(range_start: float, range_end: float) float#
Get a reproducible random floating pointer number out of a specified range, see
test_rand_int()for details on test case random numbers.Added in version 2.16.
- Parameters:
range_start – the minimum value returned by this function
range_end – the minimum value not returned by this function
- Returns:
a number with
range_start<= number <range_end.
- test_rand_int() int#
Get 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.
Added in version 2.16.
- Returns:
a random number from the seeded random number generator.
- test_rand_int_range(begin: int, end: int) int#
Get a reproducible random integer number out of a specified range, see
test_rand_int()for details on test case random numbers.Added in version 2.16.
- Parameters:
begin – the minimum value returned by this function
end – the smallest value not to be returned by this function
- Returns:
a number with
begin<= number <end.
- test_run() int#
Runs all tests under the toplevel suite which can be retrieved with
test_get_root(). Similar totest_run_suite(), the test cases to be run are filtered according to test path arguments (-p testpathand-s testpath) as parsed bytest_init().test_run_suite()ortest_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 (sincetest_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
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.
Added in version 2.16.
- Returns:
0 on success, 1 on failure (assuming it returns at all), 0 or 77 if all tests were skipped with
test_skip()and/ortest_incomplete()
- test_run_suite(suite: TestSuite) int#
Execute the tests within
suiteand all nestedTestSuite. The test suites to be executed are filtered according to test path arguments (-p testpathand-s testpath) as parsed bytest_init(). See thetest_run()documentation for more information on the order that tests are run in.test_run_suite()ortest_run()may only be called once in a program.Added in version 2.16.
- Parameters:
suite – a
TestSuite- Returns:
0 on success
- test_set_nonfatal_assertions() None#
Changes the behaviour of the various
g_assert_*()macros,test_assert_expected_messages()and the variousg_test_trap_assert_*()macros to not abort to program, but instead calltest_fail()and continue. (This also changes the behavior oftest_fail()so that it will not cause the test program to abort after completing the failed test.)Note that the
assert_not_reached()andassert()macros are not affected by this.This function can only be called after
test_init().Added in version 2.38.
- test_skip(msg: str | None = None) None#
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.
Added in version 2.38.
- Parameters:
msg – explanation
- test_subprocess() bool#
Returns
True(aftertest_init()has been called) if the test program is running undertest_trap_subprocess().Added in version 2.38.
- Returns:
Trueif the test program is running undertest_trap_subprocess().
- test_summary(summary: str) None#
Set the summary for a test, which describes what the test checks, and how it goes about checking it. 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.
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."); … }
Added in version 2.62.
- Parameters:
summary – One or two sentences summarising what the test checks, and how it checks it.
- test_timer_elapsed() float#
Get the number of seconds since the last start of the timer with
test_timer_start().Added in version 2.16.
- Returns:
the time since the last start of the timer in seconds, as a double
- test_timer_last() float#
Report the last result of
test_timer_elapsed().Added in version 2.16.
- Returns:
the last result of
test_timer_elapsed(), as a double
- test_timer_start() None#
Start a timing test. Call
test_timer_elapsed()when the task is supposed to be done. Call this function again to restart the timer.Added in version 2.16.
- test_trap_assertions(domain: str, file: str, line: int, func: str, assertion_flags: int, pattern: str) None#
- Parameters:
domain
file
line
func
assertion_flags
pattern
- test_trap_fork(usec_timeout: int, test_trap_flags: TestTrapFlags) bool#
Fork the current test program to execute a test case that might not return or that might abort.
If
usec_timeoutis non-0, the forked test case is aborted and considered failing if its run time exceeds it.The forking behavior can be configured with the
TestTrapFlagsflags.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\n"); g_printerr ("some stderr text: semagic43\n"); exit (0); // successful test run } g_test_trap_assert_passed (); g_test_trap_assert_stdout ("*somagic17*"); g_test_trap_assert_stderr ("*semagic43*"); }
Added in version 2.16.
Deprecated since version Unknown: This function is implemented only on Unix platforms, is not always reliable due to problems inherent in fork-without-exec and doesn’t set close-on-exec flag on its file descriptors. Use
test_trap_subprocess()instead.- Parameters:
usec_timeout – Timeout for the forked test in micro seconds.
test_trap_flags – Flags to modify forking behaviour.
- Returns:
Truefor the forked child andFalsefor the executing parent process.
- test_trap_has_passed() bool#
Check the result of the last
test_trap_subprocess()call.Added in version 2.16.
- Returns:
Trueif the last test subprocess terminated successfully.
- test_trap_reached_timeout() bool#
Check the result of the last
test_trap_subprocess()call.Added in version 2.16.
- Returns:
Trueif the last test subprocess got killed due to a timeout.
- test_trap_subprocess(test_path: str | None, usec_timeout: int, test_flags: TestSubprocessFlags) None#
Respawns the test program to run only
test_pathin a subprocess.This is equivalent to calling
test_trap_subprocess_with_envp()withenvpset toNone. See the documentation for that function for full details.Added in version 2.38.
- Parameters:
test_path – Test to run in a subprocess
usec_timeout – Timeout for the subprocess test in micro seconds.
test_flags – Flags to modify subprocess behaviour.
- test_trap_subprocess_with_envp(test_path: str | None, envp: list[str] | None, usec_timeout: int, test_flags: TestSubprocessFlags) None#
Respawns the test program to run only
test_pathin a subprocess with the givenenvpenvironment.This can be used for a test case that might not return, or that might abort.
If
test_pathisNonethen the same test is re-run in a subprocess. You can usetest_subprocess()to determine whether the test is in a subprocess or not.test_pathcan 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
envpisNone, the parent process’ environment will be inherited.If
usec_timeoutis non-0, the test subprocess is aborted and considered failing if its run time exceeds it.The subprocess behavior can be configured with the
TestSubprocessFlagsflags.You can use methods such as
test_trap_assert_passed(),test_trap_assert_failed(), andtest_trap_assert_stderr()to check the results of the subprocess. (But note thattest_trap_assert_stdout()andtest_trap_assert_stderr()cannot be used iftest_flagsspecifies that the child should inherit the parent stdout/stderr.)If your
main ()needs to behave differently in the subprocess, you can calltest_subprocess()(after callingtest_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 ignoreSIGCHLD, 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_autoptr(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 (); }
Added in version 2.80.
- Parameters:
test_path – Test to run in a subprocess
envp – Environment to run the test in, or
Noneto inherit the parent’s environment. This must be in the GLib filename encoding.usec_timeout – Timeout for the subprocess test in micro seconds.
test_flags – Flags to modify subprocess behaviour.
- threads_init()#
- timeout_add(interval, function, *user_data, priority=0)#
Sets a function to be called at regular intervals, with the default priority,
PRIORITY_DEFAULT.The given
functionis called repeatedly until it returnsSOURCE_REMOVEorFalse, at which point the timeout is automatically destroyed and the function will not be called again. The first call to the function will be at the end of the firstinterval.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 mainloop memory management for details on how to handle the return value and memory management of
data.If you want to have a timer in the “seconds” range and do not care about the exact time of the first call of the timer, use the
timeout_add_secondsfunction; this function allows for more optimizations and more efficient system power usage.This internally creates a main loop source using
timeout_source_newand attaches it to the globalMainContextusingattach, 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.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:
interval – the time between calls to the function, in milliseconds (1/1000ths of a second)
function – function to call
user_data
priority
- Returns:
the ID (greater than 0) of the event source.
- timeout_add_seconds(interval, function, *user_data, priority=0)#
Sets a function to be called at regular intervals with the default priority,
PRIORITY_DEFAULT.The function is called repeatedly until it returns
SOURCE_REMOVEorFalse, at which point the timeout is automatically destroyed and the function will not be called again.This internally creates a main loop source using
timeout_source_new_secondsand attaches it to the main loop context usingattach. You can do these steps manually if you need greater control. Also seetimeout_add_seconds_full.It is safe to call this function from any thread.
Note that the first call of the timer may not be precise for timeouts of one second. If you need finer precision and have such a timeout, you may want to use
timeout_addinstead.See mainloop memory management for details on how to handle the return value and memory management of
data.The interval given is in terms of monotonic time, not wall clock time. See
get_monotonic_time.Added in version 2.14.
- Parameters:
interval – the time between calls to the function, in seconds
function – function to call
user_data
priority
- Returns:
the ID (greater than 0) of the event source.
- timeout_source_new(interval: int) Source#
Creates a new timeout source.
The source will not initially be associated with any
MainContextand must be added to one withattachbefore 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.
- Returns:
the newly-created timeout source
- timeout_source_new_seconds(interval: int) Source#
Creates a new timeout source.
The source will not initially be associated with any
MainContextand must be added to one withattachbefore 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.Added in version 2.14.
- Parameters:
interval – the timeout interval in seconds
- Returns:
the newly-created timeout source
- trash_stack_height(stack_p: TrashStack) int#
- Parameters:
stack_p
- trash_stack_peek(stack_p: TrashStack) Any | None#
- Parameters:
stack_p
- trash_stack_pop(stack_p: TrashStack) Any | None#
- Parameters:
stack_p
- trash_stack_push(stack_p: TrashStack, data_p: Any) None#
- Parameters:
stack_p
data_p
- try_malloc(n_bytes: int) Any | None#
Attempts to allocate
n_bytes, and returnsNoneon failure. Contrast withmalloc(), which aborts the program on failure.- Parameters:
n_bytes – number of bytes to allocate.
- Returns:
the allocated memory, or
None.
- try_malloc0(n_bytes: int) Any | None#
Attempts to allocate
n_bytes, initialized to 0’s, and returnsNoneon failure. Contrast withmalloc0(), which aborts the program on failure.Added in version 2.8.
- Parameters:
n_bytes – number of bytes to allocate
- Returns:
the allocated memory, or
None
- try_malloc0_n(n_blocks: int, n_block_bytes: int) Any | None#
This function is similar to
try_malloc0(), allocating (n_blocks*n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.Added in version 2.24.
- Parameters:
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
- Returns:
the allocated memory, or
None
- try_malloc_n(n_blocks: int, n_block_bytes: int) Any | None#
This function is similar to
try_malloc(), allocating (n_blocks*n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.Added in version 2.24.
- Parameters:
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
- Returns:
the allocated memory, or
None.
- try_realloc(mem: Any, n_bytes: int) Any | None#
Attempts to realloc
memto a new size,n_bytes, and returnsNoneon failure. Contrast withrealloc(), which aborts the program on failure.If
memisNone, behaves the same astry_malloc().- Parameters:
mem – previously-allocated memory, or
None.n_bytes – number of bytes to allocate.
- Returns:
the allocated memory, or
None.
- try_realloc_n(mem: Any, n_blocks: int, n_block_bytes: int) Any | None#
This function is similar to
try_realloc(), allocating (n_blocks*n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.Added in version 2.24.
- Parameters:
mem – previously-allocated memory, or
None.n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
- Returns:
the allocated memory, or
None.
- ucs4_to_utf16(str: list[str]) tuple[int, int, int]#
Convert a string from UCS-4 to UTF-16. A 0 character will be added to the result after the converted text.
- Parameters:
str – a UCS-4 encoded string
- Returns:
a pointer to a newly allocated UTF-16 string. This value must be freed with
free(). If an error occurs,Nonewill be returned anderrorset.
- ucs4_to_utf8(str: list[str]) tuple[str, int, int]#
Convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8. The result will be terminated with a 0 byte.
- Parameters:
str – a UCS-4 encoded string
- Returns:
a pointer to a newly allocated UTF-8 string. This value must be freed with
free(). If an error occurs,Nonewill be returned anderrorset. In that case,items_readwill be set to the position of the first invalid input character.
- unichar_break_type(c: str) UnicodeBreakType#
Determines the break type of
c.cshould be a Unicode character (to derive a character from UTF-8 encoded text, useutf8_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
- Returns:
the break type of
c
- unichar_combining_class(uc: str) int#
Determines the canonical combining class of a Unicode character.
Added in version 2.14.
- Parameters:
uc – a Unicode character
- Returns:
the combining class of the character
- unichar_compose(a: str, b: str) tuple[bool, str]#
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 ofaorbequal 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 amp#64;amp#97;amp#44;amp#64;amp#98;. See the Unicode Standard for the definition of Primary Composite.If
aandbdo not compose a new character,chis set to zero.See UAX for details.
Added in version 2.30.
- Parameters:
a – a Unicode character
b – a Unicode character
- Returns:
Trueif the characters could be composed
- unichar_decompose(ch: str) tuple[bool, str, str]#
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
bwill be set to zero.If
chis not decomposable,ais set tochandbis set to zero.Note that the way Unicode decomposition pairs are defined, it is guaranteed that
bwould not decompose further, butamay itself decompose. To get the full canonical decomposition forch, one would need to recursively call this function ona. Or useunichar_fully_decompose().See UAX for details.
Added in version 2.30.
- Parameters:
ch – a Unicode character
- Returns:
Trueif the character could be decomposed
- unichar_digit_value(c: str) int#
Determines the numeric value of a character as a decimal digit.
- Parameters:
c – a Unicode character
- Returns:
If
cis a decimal digit (according tounichar_isdigit()), its numeric value. Otherwise, -1.
- unichar_fully_decompose(ch: str, compat: bool, result_len: int) tuple[int, str]#
Computes the canonical or compatibility decomposition of a Unicode character. For compatibility decomposition, pass
Trueforcompat; for canonical decomposition passFalseforcompat.The decomposed sequence is placed in
result. Only up toresult_lencharacters are written intoresult. The length of the full decomposition (irrespective ofresult_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 asUNICHAR_MAX_DECOMPOSITION_LENGTH.See UAX for details.
Added in version 2.30.
- Parameters:
ch – a Unicode character.
compat – whether perform canonical or compatibility decomposition
result_len – length of
result
- Returns:
the length of the full decomposition.
- unichar_get_mirror_char(ch: str) tuple[bool, str]#
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
chhas the Unicode mirrored property and there is another unicode character that typically has a glyph that is the mirror image ofch's glyph andmirrored_chis set, it puts that character in the address pointed to bymirrored_ch. Otherwise the original character is put.Added in version 2.4.
- Parameters:
ch – a Unicode character
- Returns:
Trueifchhas a mirrored character,Falseotherwise
- unichar_get_script(ch: str) UnicodeScript#
Looks up the
UnicodeScriptfor a particular character (as defined by Unicode Standard Annex #24). No check is made forchbeing 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.
Added in version 2.14.
- Parameters:
ch – a Unicode character
- Returns:
the
UnicodeScriptfor the character.
- unichar_isalnum(c: str) bool#
Determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with
utf8_get_char().- Parameters:
c – a Unicode character
- Returns:
Trueifcis an alphanumeric character
- unichar_isalpha(c: str) bool#
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
- Returns:
Trueifcis an alphabetic character
- unichar_iscntrl(c: str) bool#
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
- Returns:
Trueifcis a control character
- unichar_isdefined(c: str) bool#
Determines if a given character is assigned in the Unicode standard.
- Parameters:
c – a Unicode character
- Returns:
Trueif the character has an assigned value
- unichar_isdigit(c: str) bool#
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
- Returns:
Trueifcis a digit
- unichar_isgraph(c: str) bool#
Determines whether a character is printable and not a space (returns
Falsefor control characters, format characters, and spaces).unichar_isprint()is similar, but returnsTruefor spaces. Given some UTF-8 text, obtain a character value withutf8_get_char().- Parameters:
c – a Unicode character
- Returns:
Trueifcis printable unless it’s a space
- unichar_islower(c: str) bool#
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
- Returns:
Trueifcis a lowercase letter
- unichar_ismark(c: str) bool#
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.
Added in version 2.14.
- Parameters:
c – a Unicode character
- Returns:
Trueifcis a mark character
- unichar_isprint(c: str) bool#
Determines whether a character is printable. Unlike
unichar_isgraph(), returnsTruefor spaces. Given some UTF-8 text, obtain a character value withutf8_get_char().- Parameters:
c – a Unicode character
- Returns:
Trueifcis printable
- unichar_ispunct(c: str) bool#
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
- Returns:
Trueifcis a punctuation or symbol character
- unichar_isspace(c: str) bool#
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
- Returns:
Trueifcis a space character
- unichar_istitle(c: str) bool#
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
- Returns:
Trueif the character is titlecase
- unichar_isupper(c: str) bool#
Determines if a character is uppercase.
- Parameters:
c – a Unicode character
- Returns:
Trueifcis an uppercase character
- unichar_iswide(c: str) bool#
Determines if a character is typically rendered in a double-width cell.
- Parameters:
c – a Unicode character
- Returns:
Trueif the character is wide
- unichar_iswide_cjk(c: str) bool#
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 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 andunichar_iszerowidth().Added in version 2.12.
- Parameters:
c – a Unicode character
- Returns:
Trueif the character is wide in legacy East Asian locales
- unichar_isxdigit(c: str) bool#
Determines if a character is a hexadecimal digit.
- Parameters:
c – a Unicode character.
- Returns:
Trueif the character is a hexadecimal digit
- unichar_iszerowidth(c: str) bool#
Determines if a given character typically takes zero width when rendered. The return value is
Truefor 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()orunichar_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.Added in version 2.14.
- Parameters:
c – a Unicode character
- Returns:
Trueif the character has zero width
- unichar_to_utf8(c: str) tuple[int, str]#
Converts a single character to UTF-8.
- Parameters:
c – a Unicode character code
- Returns:
number of bytes written
- unichar_tolower(c: str) str#
Converts a character to lower case.
- Parameters:
c – a Unicode character.
- Returns:
the result of converting
cto lower case. Ifcis not an upperlower or titlecase character, or has no lowercase equivalentcis returned unchanged.
- unichar_totitle(c: str) str#
Converts a character to the titlecase.
- Parameters:
c – a Unicode character
- Returns:
the result of converting
cto titlecase. Ifcis not an uppercase or lowercase character,cis returned unchanged.
- unichar_toupper(c: str) str#
Converts a character to uppercase.
- Parameters:
c – a Unicode character
- Returns:
the result of converting
cto uppercase. Ifcis not a lowercase or titlecase character, or has no upper case equivalentcis returned unchanged.
- unichar_type(c: str) UnicodeType#
Classifies a Unicode character by type.
- Parameters:
c – a Unicode character
- Returns:
the type of the character.
- unichar_validate(ch: str) bool#
Checks whether
chis a valid Unicode character. Some possible integer values ofchwill not be valid. 0 is considered a valid character, though it’s normally a string terminator.- Parameters:
ch – a Unicode character
- Returns:
Trueifchis a valid Unicode character
- unichar_xdigit_value(c: str) int#
Determines the numeric value of a character as a hexadecimal digit.
- Parameters:
c – a Unicode character
- Returns:
If
cis a hex digit (according tounichar_isxdigit()), its numeric value. Otherwise, -1.
- unicode_canonical_decomposition(ch: str, result_len: int) str#
Computes the canonical decomposition of a Unicode character.
Deprecated since version 2.30: Use the more flexible
unichar_fully_decompose()instead.- Parameters:
ch – a Unicode character.
result_len – location to store the length of the return value.
- Returns:
a newly allocated string of Unicode characters.
result_lenis set to the resulting length of the string.
- unicode_canonical_ordering(string: list[str]) None#
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.
- unicode_script_from_iso15924(iso15924: int) UnicodeScript#
- Parameters:
iso15924
- unicode_script_to_iso15924(script: UnicodeScript) int#
- Parameters:
script
- unix_fd_add_full(priority: int, fd: int, condition: IOCondition, function: Callable[[int, IOCondition, Any], bool], user_data: Any = None) int#
Sets a function to be called when the IO condition, as specified by
conditionbecomes true forfd.This is the same as
unix_fd_add(), except that it allows you to specify a non-default priority and a provide aDestroyNotifyforuser_data.Added in version 2.36.
- Parameters:
priority – the priority of the source
fd – a file descriptor
condition – IO conditions to watch for on
fdfunction – a
UnixFDSourceFuncuser_data – data to pass to
function
- Returns:
the ID (greater than 0) of the event source
- unix_fd_source_new(fd: int, condition: IOCondition) Source#
Creates a
Sourceto 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
Sourcemust have typeUnixFDSourceFunc.Added in version 2.36.
- Parameters:
fd – a file descriptor
condition – I/O conditions to watch for on
fd
- Returns:
the newly created
Source
- unix_get_passwd_entry(user_name: str) Any | None#
Get the
passwdfile entry for the givenuser_nameusinggetpwnam_r(). This can fail if the givenuser_namedoesn’t exist.The returned
struct passwdhas been allocated usingmalloc()and should be freed usingfree(). The strings referenced by the returned struct are included in the same allocation, so are valid until thestruct passwdis freed.This function is safe to call from multiple threads concurrently.
You will need to include
pwd.hto get the definition ofstruct passwd.Added in version 2.64.
- Parameters:
user_name – the username to get the passwd file entry for
- Returns:
passwd entry, or
Noneon error; free the returned value withfree()
- unix_open_pipe(fds: list[int], flags: int) bool#
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) andO_NONBLOCK. Prior to GLib 2.78, onlyFD_CLOEXECwas supported — if you wanted to configureO_NONBLOCKthen that had to be done separately withfcntl().Since GLib 2.80, the constants
READandWRITEcan be used as mnemonic indexes infds.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_CLOEXECin, rather thanFD_CLOEXEC, as that matches the underlyingpipe()API more closely. Prior to 2.78, onlyFD_CLOEXECwas supported. Support forFD_CLOEXECmay be deprecated and removed in future.Added in version 2.30.
- Parameters:
fds – Array of two integers
flags – Bitfield of file descriptor flags, as for fcntl()
- Returns:
Trueon success,Falseif not (and errno will be set).
- unix_set_fd_nonblocking(fd: int, nonblock: bool) bool#
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.Added in version 2.30.
- Parameters:
fd – A file descriptor
nonblock – If
True, set the descriptor to be non-blocking
- Returns:
Trueif successful
- unix_signal_add(priority: int, signum: int, handler: Callable[[Any], bool], user_data: Any = None) int#
A convenience function for
unix_signal_source_new(), which attaches to the defaultMainContext. You can remove the watch usingremove().Added in version 2.30.
- Parameters:
priority
signum – Signal number
handler – Callback
user_data – Data for
handler
- Returns:
An ID (greater than 0) for the event source
- unix_signal_add_full(priority: int, signum: int, handler: Callable[[Any], bool], user_data: Any = None) int#
A convenience function for
unix_signal_source_new(), which attaches to the defaultMainContext. You can remove the watch usingremove().Added in version 2.30.
Deprecated since version PyGObject-3.16.0: GLib.unix_signal_add_full is deprecated; use GLib.unix_signal_add instead
- Parameters:
priority – the priority of the signal source. Typically this will be in the range between
PRIORITY_DEFAULTandPRIORITY_HIGH.signum – Signal number
handler – Callback
user_data – Data for
handler
- Returns:
An ID (greater than 0) for the event source
- unix_signal_source_new(signum: int) Source#
Create a
Sourcethat will be dispatched upon delivery of the UNIX signalsignum. In GLib versions before 2.36, onlySIGHUP,SIGINT,SIGTERMcan be monitored. In GLib 2.36,SIGUSR1andSIGUSR2were added. In GLib 2.54,SIGWINCHwas added.Note that unlike the UNIX default, all sources which have created a watch will be dispatched, regardless of which underlying thread invoked
unix_signal_source_new().For example, an effective use of this function is to handle
SIGTERMcleanly; flushing any outstanding files, and then callingquit(). 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
MainContextand must be added to one withattach()before it will be executed.Added in version 2.30.
- Parameters:
signum – A signal number
- Returns:
A newly created
Source
- unlink(filename: str) int#
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.
Added in version 2.6.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
- Returns:
0 if the name was successfully deleted, -1 if an error occurred
- unsetenv(variable: str) None#
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 withenviron_setenv()andenviron_unsetenv(), and then pass that array directly to execvpe(),spawn_async(), or the like.Added in version 2.4.
- Parameters:
variable – the environment variable to remove, must not contain ‘=’
- uri_build(flags: UriFlags, scheme: str, userinfo: str | None, host: str | None, port: int, path: str, query: str | None = None, fragment: str | None = None) Uri#
- Parameters:
flags
scheme
userinfo
host
port
path
query
fragment
- uri_build_with_user(flags: UriFlags, scheme: str, user: str | None, password: str | None, auth_params: str | None, host: str | None, port: int, path: str, query: str | None = None, fragment: str | None = None) Uri#
- Parameters:
flags
scheme
user
password
auth_params
host
port
path
query
fragment
- uri_escape_bytes(unescaped: list[int], reserved_chars_allowed: str | None = None) str#
- Parameters:
unescaped
reserved_chars_allowed
- uri_escape_string(unescaped: str, reserved_chars_allowed: str | None, allow_utf8: bool) str#
- Parameters:
unescaped
reserved_chars_allowed
allow_utf8
- uri_join(flags: UriFlags, scheme: str | None, userinfo: str | None, host: str | None, port: int, path: str, query: str | None = None, fragment: str | None = None) str#
- Parameters:
flags
scheme
userinfo
host
port
path
query
fragment
- uri_join_with_user(flags: UriFlags, scheme: str | None, user: str | None, password: str | None, auth_params: str | None, host: str | None, port: int, path: str, query: str | None = None, fragment: str | None = None) str#
- Parameters:
flags
scheme
user
password
auth_params
host
port
path
query
fragment
- uri_parse_params(params: str, length: int, separators: str, flags: UriParamsFlags) dict[str, str]#
- Parameters:
params
length
separators
flags
- uri_resolve_relative(base_uri_string: str | None, uri_ref: str, flags: UriFlags) str#
- Parameters:
base_uri_string
uri_ref
flags
- uri_split(uri_ref: str, flags: UriFlags) tuple[bool, str | None, str | None, str | None, int, str, str | None, str | None]#
- Parameters:
uri_ref
flags
- uri_split_network(uri_string: str, flags: UriFlags) tuple[bool, str | None, str | None, int]#
- Parameters:
uri_string
flags
- uri_split_with_user(uri_ref: str, flags: UriFlags) tuple[bool, str | None, str | None, str | None, str | None, str | None, int, str, str | None, str | None]#
- Parameters:
uri_ref
flags
- uri_unescape_bytes(escaped_string: str, length: int, illegal_characters: str | None = None) Bytes#
- Parameters:
escaped_string
length
illegal_characters
- uri_unescape_segment(escaped_string: str | None = None, escaped_string_end: str | None = None, illegal_characters: str | None = None) str | None#
- Parameters:
escaped_string
escaped_string_end
illegal_characters
- uri_unescape_string(escaped_string: str, illegal_characters: str | None = None) str | None#
- Parameters:
escaped_string
illegal_characters
- usleep(microseconds: int) None#
Pauses the current thread for the given number of microseconds.
There are 1 million microseconds per second (represented by the
USEC_PER_SECmacro).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(str: list[int]) tuple[str, int, int]#
Convert a string from UTF-16 to UCS-4. The result will be nul-terminated.
- Parameters:
str – a UTF-16 encoded string
- Returns:
a pointer to a newly allocated UCS-4 string. This value must be freed with
free(). If an error occurs,Nonewill be returned anderrorset.
- utf16_to_utf8(str: list[int]) tuple[str, int, int]#
Convert a string from UTF-16 to UTF-8. The result will be terminated with a 0 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 e.g. 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
- Returns:
a pointer to a newly allocated UTF-8 string. This value must be freed with
free(). If an error occurs,Nonewill be returned anderrorset.
- utf8_casefold(str: str, len: int) str#
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 byutf8_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 string
len – length of
str, in bytes, or -1 ifstris nul-terminated.
- Returns:
a newly allocated string, that is a case independent form of
str.
- utf8_collate(str1: str, str2: str) int#
Compares two strings for ordering using the linguistically correct rules for the [current locale][setlocale]. 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 string
str2 – a UTF-8 encoded string
- Returns:
< 0 if
str1compares beforestr2, 0 if they compare equal, > 0 ifstr1compares afterstr2.
- utf8_collate_key(str: str, len: int) str#
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][setlocale].
- Parameters:
str – a UTF-8 encoded string.
len – length of
str, in bytes, or -1 ifstris nul-terminated.
- Returns:
a newly allocated string. This string should be freed with
free()when you are done with it.
- utf8_collate_key_for_filename(str: str, len: int) str#
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][setlocale].
Added in version 2.8.
- Parameters:
str – a UTF-8 encoded string.
len – length of
str, in bytes, or -1 ifstris nul-terminated.
- Returns:
a newly allocated string. This string should be freed with
free()when you are done with it.
- utf8_find_next_char(p: str, end: str | None = None) str | None#
Finds the start of the next UTF-8 character in the string after
p.pdoes 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
endisNone, the return value will never beNone: if the end of the string is reached, a pointer to the terminating nul byte is returned. Ifendis non-None, the return value will beNoneif the end of the string is reached.- Parameters:
p – a pointer to a position within a UTF-8 encoded string
end – a pointer to the byte following the end of the string, or
Noneto indicate that the string is nul-terminated
- Returns:
a pointer to the found character or
Noneifendis set and is reached
- utf8_find_prev_char(str: str, p: str) str | None#
Given a position
pwith a UTF-8 encoded stringstr, find the start of the previous UTF-8 character starting beforep. ReturnsNoneif no UTF-8 characters are present instrbeforep.pdoes 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 string
p – pointer to some position within
str
- Returns:
a pointer to the found character or
None.
- utf8_get_char(p: str) str#
Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
If
pdoes 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 useutf8_get_char_validated()instead.- Parameters:
p – a pointer to Unicode character encoded as UTF-8
- Returns:
the resulting character
- utf8_get_char_validated(p: str, max_len: int) str#
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 ifmax_lenis 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-8
max_len – the maximum number of bytes to read, or -1 if
pis nul-terminated
- Returns:
the resulting character. If
ppoints to a partial sequence at the end of a string that could begin a valid character (or ifmax_lenis zero), returns (gunichar)-2; otherwise, ifpdoes not point to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.
- utf8_make_valid(str: str, len: int) str#
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.
Added in version 2.52.
- Parameters:
str – string to coerce into UTF-8
len – the maximum length of
strto use, in bytes. Iflen< 0, then the string is nul-terminated.
- Returns:
a valid UTF-8 string whose content resembles
str
- utf8_normalize(str: str, len: int, mode: NormalizeMode) str | None#
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
Noneis returned. You should generally callutf8_normalize()before comparing two Unicode strings.The normalization mode
DEFAULTonly standardizes differences that do not affect the text content, such as the above-mentioned accent representation.ALLalso 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.DEFAULT_COMPOSEandALL_COMPOSEare likeDEFAULTandALL, 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 of
str, in bytes, or -1 ifstris nul-terminated.mode – the type of normalization to perform.
- Returns:
a newly allocated string, that is the normalized form of
str, orNoneifstris not valid UTF-8.
- utf8_offset_to_pointer(str: str, offset: int) str#
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
offsetto step backwards. It is usually worth stepping backwards from the end instead of forwards ifoffsetis 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 thatoffsetis within string boundaries before calling that function. Callutf8_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 string
offset – a character offset within
str
- Returns:
the resulting pointer
- utf8_pointer_to_offset(str: str, pos: str) int#
Converts from a pointer to position within a string to an integer character offset.
Since 2.10, this function allows
posto be beforestr, and returns a negative offset in this case.- Parameters:
str – a UTF-8 encoded string
pos – a pointer to a position within
str
- Returns:
the resulting character offset
- utf8_prev_char(p: str) str#
Finds the previous UTF-8 character in the string before
p.pdoes 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. Ifpmight be the first character of the string, you must useutf8_find_prev_char()instead.- Parameters:
p – a pointer to a position within a UTF-8 encoded string
- Returns:
a pointer to the found character
- utf8_strchr(p: str, len: int, c: str) str | None#
Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to
lenbytes. Iflenis -1, allow unbounded search.- Parameters:
p – a nul-terminated UTF-8 encoded string
len – the maximum length of
pc – a Unicode character
- Returns:
Noneif the string does not contain the character, otherwise, a pointer to the start of the leftmost occurrence of the character in the string.
- utf8_strdown(str: str, len: int) str#
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 string
len – length of
str, in bytes, or -1 ifstris nul-terminated.
- Returns:
a newly allocated string, with all characters converted to lowercase.
- utf8_strlen(p: str, max: int) int#
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 string
max – the maximum number of bytes to examine. If
maxis less than 0, then the string is assumed to be nul-terminated. Ifmaxis 0,pwill not be examined and may beNone. Ifmaxis greater than 0, up tomaxbytes are examined
- Returns:
the length of the string in characters
- utf8_strncpy(dest: str, src: str, n: int) str#
Like the standard C strncpy() function, but copies a given number of characters instead of a given number of bytes. The
srcstring must be valid UTF-8 encoded text. (Useutf8_validate()on all text before trying to use UTF-8 utility functions with it.)Note you must ensure
destis at least 4 *n+ 1 to fit the largest possible UTF-8 characters- Parameters:
dest – buffer to fill with characters from
srcsrc – UTF-8 encoded string
n – character count
- Returns:
dest
- utf8_strrchr(p: str, len: int, c: str) str | None#
Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to
lenbytes. Iflenis -1, allow unbounded search.- Parameters:
p – a nul-terminated UTF-8 encoded string
len – the maximum length of
pc – a Unicode character
- Returns:
Noneif the string does not contain the character, otherwise, a pointer to the start of the rightmost occurrence of the character in the string.
- utf8_strreverse(str: str, len: int) str#
Reverses a UTF-8 string.
strmust be valid UTF-8 encoded text. (Useutf8_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 withfree()when no longer needed.Added in version 2.2.
- Parameters:
str – a UTF-8 encoded string
len – the maximum length of
strto use, in bytes. Iflen< 0, then the string is nul-terminated.
- Returns:
a newly-allocated string which is the reverse of
str
- utf8_strup(str: str, len: int) str#
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 string
len – length of
str, in bytes, or -1 ifstris nul-terminated.
- Returns:
a newly allocated string, with all characters converted to uppercase.
- utf8_substring(str: str, start_pos: int, end_pos: int) str#
Copies a substring out of a UTF-8 encoded string. The substring will contain
end_pos-start_poscharacters.Since GLib 2.72,
-1can be passed toend_posto indicate the end of the string.Added in version 2.30.
- Parameters:
str – a UTF-8 encoded string
start_pos – a character offset within
strend_pos – another character offset within
str, or-1to indicate the end of the string
- Returns:
a newly allocated copy of the requested substring. Free with
free()when no longer needed.
- utf8_to_ucs4(str: str, len: int) tuple[str, int, int]#
Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4. A trailing 0 character will be added to the string after the converted text.
- Parameters:
str – a UTF-8 encoded string
len – the maximum length of
strto use, in bytes. Iflen< 0, then the string is nul-terminated.
- Returns:
a pointer to a newly allocated UCS-4 string. This value must be freed with
free(). If an error occurs,Nonewill be returned anderrorset.
- utf8_to_ucs4_fast(str: str, len: int) tuple[str, int]#
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 0 character will be added to the string after the converted text.- Parameters:
str – a UTF-8 encoded string
len – the maximum length of
strto use, in bytes. Iflen< 0, then the string is nul-terminated.
- Returns:
a pointer to a newly allocated UCS-4 string. This value must be freed with
free().
- utf8_to_utf16(str: str, len: int) tuple[int, int, int]#
Convert a string from UTF-8 to UTF-16. A 0 character will be added to the result after the converted text.
- Parameters:
str – a UTF-8 encoded string
len – the maximum length (number of bytes) of
strto use. Iflen< 0, then the string is nul-terminated.
- Returns:
a pointer to a newly allocated UTF-16 string. This value must be freed with
free(). If an error occurs,Nonewill be returned anderrorset.
- utf8_truncate_middle(string: str, truncate_length: int) str#
Cuts off the middle of the string, preserving half of
truncate_lengthcharacters at the beginning and half at the end.If
stringis already short enough, this returns a copy ofstring. Iftruncate_lengthis0, an empty string is returned.Added in version 2.78.
- Parameters:
string – a nul-terminated UTF-8 encoded string
truncate_length – the new size of
string, in characters, including the ellipsis character
- Returns:
a newly-allocated copy of
stringellipsized in the middle
- utf8_validate(str: list[int]) tuple[bool, str]#
Validates UTF-8 encoded text.
stris the text to validate; ifstris nul-terminated, thenmax_lencan be -1, otherwisemax_lenshould be the number of bytes to validate. Ifendis non-None, then the end of the valid range will be stored there (i.e. the start of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise).Note that
utf8_validate()returnsFalseifmax_lenis positive and any of themax_lenbytes are nul.Returns
Trueif all ofstrwas valid. Many GLib and GTK routines require valid UTF-8 as input; so data read from a file or the network should be checked withutf8_validate()before doing anything else with it.- Parameters:
str – a pointer to character data
- Returns:
Trueif the text was valid UTF-8
- utf8_validate_len(str: list[int]) tuple[bool, str]#
Validates UTF-8 encoded text.
As with
utf8_validate(), butmax_lenmust be set, and hence this function will always returnFalseif any of the bytes ofstrare nul.Added in version 2.60.
- Parameters:
str – a pointer to character data
- Returns:
Trueif the text was valid UTF-8
- utime(filename: str, utb: Any = 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.
Added in version 2.18.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
utb – a pointer to a struct utimbuf.
- Returns:
0 if the operation was successful, -1 if an error occurred
- uuid_string_is_valid(str: str) bool#
Parses the string
strand 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.
Added in version 2.52.
- Parameters:
str – a string representing a UUID
- Returns:
Trueifstris a valid UUID,Falseotherwise.
- uuid_string_random() str#
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.Added in version 2.52.
- Returns:
A string that should be freed with
free().
- variant_get_gtype() GType#
- variant_parse(type: VariantType | None, text: str, limit: str | None = None, endptr: str | None = None) Variant#
- Parameters:
type
text
limit
endptr
- variant_type_checked_(type_string: str) VariantType#
- Parameters:
type_string