Functions

  access (filename, mode)
  ascii_digit_value (c)
  ascii_dtostr (buffer, buf_len, d)
  ascii_formatd (buffer, buf_len, format, d)
  ascii_strcasecmp (s1, s2)
  ascii_strdown (str, len)
  ascii_string_to_signed (str, base, min, max)
  ascii_string_to_unsigned (str, base, min, max)
  ascii_strncasecmp (s1, s2, n)
  ascii_strtod (nptr)
  ascii_strtoll (nptr, base)
  ascii_strtoull (nptr, base)
  ascii_strup (str, len)
  ascii_tolower (c)
  ascii_toupper (c)
  ascii_xdigit_value (c)
  assert_warning (log_domain, file, line, pretty_function, expression)
  assertion_message (domain, file, line, func, message)
  assertion_message_cmpstr (domain, file, line, func, expr, arg1, cmp, arg2)
  assertion_message_error (domain, file, line, func, expr, error, error_domain, error_code)
  atexit (func)
  atomic_int_add (atomic, val)
  atomic_int_and (atomic, val)
  atomic_int_compare_and_exchange (atomic, oldval, newval)
  atomic_int_dec_and_test (atomic)
  atomic_int_exchange_and_add (atomic, val)
  atomic_int_get (atomic)
  atomic_int_inc (atomic)
  atomic_int_or (atomic, val)
  atomic_int_set (atomic, newval)
  atomic_int_xor (atomic, val)
  atomic_pointer_add (atomic, val)
  atomic_pointer_and (atomic, val)
  atomic_pointer_compare_and_exchange (atomic, oldval, newval)
  atomic_pointer_get (atomic)
  atomic_pointer_or (atomic, val)
  atomic_pointer_set (atomic, newval)
  atomic_pointer_xor (atomic, val)
  atomic_rc_box_acquire (mem_block)
  atomic_rc_box_alloc (block_size)
  atomic_rc_box_alloc0 (block_size)
  atomic_rc_box_dup (block_size, mem_block)
  atomic_rc_box_get_size (mem_block)
  atomic_rc_box_release (mem_block)
  atomic_rc_box_release_full (mem_block, clear_func)
  base64_decode (text)
  base64_decode_inplace (text)
  base64_encode (data)
  base64_encode_close (break_lines, state, save)
  base64_encode_step (in_, break_lines, state, save)
  basename (file_name)
  bit_lock (address, lock_bit)
  bit_nth_lsf (mask, nth_bit)
  bit_nth_msf (mask, nth_bit)
  bit_storage (number)
  bit_trylock (address, lock_bit)
  bit_unlock (address, lock_bit)
  bookmark_file_error_quark ()
  build_filenamev (args)
  build_pathv (separator, args)
  byte_array_free (array, free_segment)
  byte_array_free_to_bytes (array)
  byte_array_new ()
  byte_array_new_take (data)
  byte_array_unref (array)
  canonicalize_filename (filename, relative_to)
  chdir (path)
  check_version (required_major, required_minor, required_micro)
  checksum_type_get_length (checksum_type)
  child_watch_add (priority, pid, function, *data)
  child_watch_source_new (pid)
  clear_error ()
  close (fd)
  compute_checksum_for_bytes (checksum_type, data)
  compute_checksum_for_data (checksum_type, data)
  compute_checksum_for_string (checksum_type, str, length)
  compute_hmac_for_bytes (digest_type, key, data)
  compute_hmac_for_data (digest_type, key, data)
  compute_hmac_for_string (digest_type, key, str, length)
  convert (str, to_codeset, from_codeset)
  convert_error_quark ()
  convert_with_fallback (str, to_codeset, from_codeset, fallback)
  datalist_foreach (datalist, func, *user_data)
  datalist_get_data (datalist, key)
  datalist_get_flags (datalist)
  datalist_id_get_data (datalist, key_id)
  datalist_set_flags (datalist, flags)
  datalist_unset_flags (datalist, flags)
  dataset_destroy (dataset_location)
  dataset_foreach (dataset_location, func, *user_data)
  dataset_id_get_data (dataset_location, key_id)
  date_get_days_in_month (month, year)
  date_get_monday_weeks_in_year (year)
  date_get_sunday_weeks_in_year (year)
  date_is_leap_year (year)
  date_strftime (s, slen, format, date)
  date_time_compare (dt1, dt2)
  date_time_equal (dt1, dt2)
  date_time_hash (datetime)
  date_valid_day (day)
  date_valid_dmy (day, month, year)
  date_valid_julian (julian_date)
  date_valid_month (month)
  date_valid_weekday (weekday)
  date_valid_year (year)
  dcgettext (domain, msgid, category)
  dgettext (domain, msgid)
  dir_make_tmp (tmpl)
  direct_equal (v1, v2)
  direct_hash (v)
  dngettext (domain, msgid, msgid_plural, n)
  double_equal (v1, v2)
  double_hash (v)
  dpgettext (domain, msgctxtid, msgidoffset)
  dpgettext2 (domain, context, msgid)
  environ_getenv (envp, variable)
  environ_setenv (envp, variable, value, overwrite)
  environ_unsetenv (envp, variable)
  file_error_from_errno (err_no)
  file_error_quark ()
  file_get_contents (filename)
  file_open_tmp (tmpl)
  file_read_link (filename)
  file_set_contents (filename, contents)
  file_test (filename, test)
  filename_display_basename (filename)
  filename_display_name (filename)
  filename_from_uri (uri)
  filename_from_utf8 (utf8string, len)
  filename_to_uri (filename, hostname)
  filename_to_utf8 (opsysstring, len)
  find_program_in_path (program)
  format_size (size)
  format_size_for_display (size)
  format_size_full (size, flags)
  free (mem)
  get_application_name ()
  get_charset ()
  get_codeset ()
  get_current_dir ()
  get_current_time ()
  get_environ ()
  get_filename_charsets ()
  get_home_dir ()
  get_host_name ()
  get_language_names ()
  get_language_names_with_category (category_name)
  get_locale_variants (locale)
  get_monotonic_time ()
  get_num_processors ()
  get_prgname ()
  get_real_name ()
  get_real_time ()
  get_system_config_dirs ()
  get_system_data_dirs ()
  get_tmp_dir ()
  get_user_cache_dir ()
  get_user_config_dir ()
  get_user_data_dir ()
  get_user_name ()
  get_user_runtime_dir ()
  get_user_special_dir (directory)
  getenv (variable)
  hash_table_add (hash_table, key)
  hash_table_contains (hash_table, key)
  hash_table_destroy (hash_table)
  hash_table_insert (hash_table, key, value)
  hash_table_lookup (hash_table, key)
  hash_table_lookup_extended (hash_table, lookup_key)
  hash_table_remove (hash_table, key)
  hash_table_remove_all (hash_table)
  hash_table_replace (hash_table, key, value)
  hash_table_size (hash_table)
  hash_table_steal (hash_table, key)
  hash_table_steal_all (hash_table)
  hash_table_steal_extended (hash_table, lookup_key)
  hash_table_unref (hash_table)
  hook_destroy (hook_list, hook_id)
  hook_destroy_link (hook_list, hook)
  hook_free (hook_list, hook)
  hook_insert_before (hook_list, sibling, hook)
  hook_prepend (hook_list, hook)
  hook_unref (hook_list, hook)
  hostname_is_ascii_encoded (hostname)
  hostname_is_ip_address (hostname)
  hostname_is_non_ascii (hostname)
  hostname_to_ascii (hostname)
  hostname_to_unicode (hostname)
  idle_add (priority, function, *data)
  idle_remove_by_data (data)
  idle_source_new ()
  int64_equal (v1, v2)
  int64_hash (v)
  int_equal (v1, v2)
  int_hash (v)
  intern_static_string (string)
  intern_string (string)
  io_add_watch (channel, priority, condition, func, *user_data)
  io_channel_error_from_errno (en)
  io_channel_error_quark ()
  io_create_watch (channel, condition)
  key_file_error_quark ()
  listenv ()
  locale_from_utf8 (utf8string, len)
  locale_to_utf8 (opsysstring)
  log_default_handler (log_domain, log_level, message, unused_data)
  log_remove_handler (log_domain, handler_id)
  log_set_always_fatal (fatal_mask)
  log_set_fatal_mask (log_domain, fatal_mask)
  log_set_handler (log_domain, log_levels, log_func, *user_data)
  log_set_writer_func (*user_data)
  log_structured_array (log_level, fields)
  log_variant (log_domain, log_level, fields)
  log_writer_default (log_level, fields, user_data)
  log_writer_format_fields (log_level, fields, use_color)
  log_writer_is_journald (output_fd)
  log_writer_journald (log_level, fields, user_data)
  log_writer_standard_streams (log_level, fields, user_data)
  log_writer_supports_color (output_fd)
  main_context_default ()
  main_context_get_thread_default ()
  main_context_ref_thread_default ()
  main_current_source ()
  main_depth ()
  malloc (n_bytes)
  malloc0 (n_bytes)
  malloc0_n (n_blocks, n_block_bytes)
  malloc_n (n_blocks, n_block_bytes)
  markup_error_quark ()
  markup_escape_text (text, length)
  mem_is_system_malloc ()
  mem_profile ()
  mem_set_vtable (vtable)
  memdup (mem, byte_size)
  mkdir_with_parents (pathname, mode)
  nullify_pointer (nullify_location)
  number_parser_error_quark ()
  on_error_query (prg_name)
  on_error_stack_trace (prg_name)
  once_init_enter (location)
  once_init_leave (location, result)
  option_error_quark ()
  parse_debug_string (string, keys)
  path_get_basename (file_name)
  path_get_dirname (file_name)
  path_is_absolute (file_name)
  path_skip_root (file_name)
  pattern_match (pspec, string_length, string, string_reversed)
  pattern_match_simple (pattern, string)
  pattern_match_string (pspec, string)
  pointer_bit_lock (address, lock_bit)
  pointer_bit_trylock (address, lock_bit)
  pointer_bit_unlock (address, lock_bit)
  poll (fds, nfds, timeout)
  propagate_error (src)
  quark_from_static_string (string)
  quark_from_string (string)
  quark_to_string (quark)
  quark_try_string (string)
  random_double ()
  random_double_range (begin, end)
  random_int ()
  random_int_range (begin, end)
  random_set_seed (seed)
  rc_box_acquire (mem_block)
  rc_box_alloc (block_size)
  rc_box_alloc0 (block_size)
  rc_box_dup (block_size, mem_block)
  rc_box_get_size (mem_block)
  rc_box_release (mem_block)
  rc_box_release_full (mem_block, clear_func)
  realloc (mem, n_bytes)
  realloc_n (mem, n_blocks, n_block_bytes)
  ref_string_acquire (str)
  ref_string_length (str)
  ref_string_new (str)
  ref_string_new_intern (str)
  ref_string_new_len (str, len)
  ref_string_release (str)
  regex_check_replacement (replacement)
  regex_error_quark ()
  regex_escape_nul (string, length)
  regex_escape_string (string)
  regex_match_simple (pattern, string, compile_options, match_options)
  regex_split_simple (pattern, string, compile_options, match_options)
  reload_user_special_dirs_cache ()
  rmdir (filename)
  sequence_get (iter)
  sequence_insert_before (iter, data)
  sequence_move (src, dest)
  sequence_move_range (dest, begin, end)
  sequence_range_get_midpoint (begin, end)
  sequence_remove (iter)
  sequence_remove_range (begin, end)
  sequence_set (iter, data)
  sequence_swap (a, b)
  set_application_name (application_name)
  set_error_literal (domain, code, message)
  set_prgname (prgname)
  setenv (variable, value, overwrite)
  shell_error_quark ()
  shell_parse_argv (command_line)
  shell_quote (unquoted_string)
  shell_unquote (quoted_string)
  slice_alloc (block_size)
  slice_alloc0 (block_size)
  slice_copy (block_size, mem_block)
  slice_free1 (block_size, mem_block)
  slice_free_chain_with_offset (block_size, mem_chain, next_offset)
  slice_get_config (ckey)
  slice_get_config_state (ckey, address, n_values)
  slice_set_config (ckey, value)
  source_remove (tag)
  source_remove_by_funcs_user_data (funcs, user_data)
  source_remove_by_user_data (user_data)
  source_set_name_by_id (tag, name)
  spaced_primes_closest (num)
  spawn_async (argv, envp=None, working_directory=None, flags=GLib.SpawnFlags.DEFAULT, child_setup=None, user_data=None, standard_input=False, standard_output=False, standard_error=False)
  spawn_async_with_fds (working_directory, argv, envp, flags, child_setup, user_data, stdin_fd, stdout_fd, stderr_fd)
  spawn_async_with_pipes (working_directory, argv, envp, flags, child_setup, *user_data)
  spawn_check_exit_status (exit_status)
  spawn_close_pid (pid)
  spawn_command_line_async (command_line)
  spawn_command_line_sync (command_line)
  spawn_error_quark ()
  spawn_exit_error_quark ()
  spawn_sync (working_directory, argv, envp, flags, child_setup, *user_data)
  stpcpy (dest, src)
  str_equal (v1, v2)
  str_has_prefix (str, prefix)
  str_has_suffix (str, suffix)
  str_hash (v)
  str_is_ascii (str)
  str_match_string (search_term, potential_hit, accept_alternates)
  str_to_ascii (str, from_locale)
  str_tokenize_and_fold (string, translit_locale)
  strcanon (string, valid_chars, substitutor)
  strcasecmp (s1, s2)
  strchomp (string)
  strchug (string)
  strcmp0 (str1, str2)
  strcompress (source)
  strdelimit (string, delimiters, new_delimiter)
  strdown (string)
  strdup (str)
  strerror (errnum)
  strescape (source, exceptions)
  strfreev (str_array)
  string_new (init)
  string_new_len (init, len)
  string_sized_new (dfl_size)
  strip_context (msgid, msgval)
  strjoinv (separator, str_array)
  strlcat (dest, src, dest_size)
  strlcpy (dest, src, dest_size)
  strncasecmp (s1, s2, n)
  strndup (str, n)
  strnfill (length, fill_char)
  strreverse (string)
  strrstr (haystack, needle)
  strrstr_len (haystack, haystack_len, needle)
  strsignal (signum)
  strstr_len (haystack, haystack_len, needle)
  strtod (nptr)
  strup (string)
  strv_contains (strv, str)
  strv_get_type ()
  strv_length (str_array)
  test_add_data_func (testpath, test_data, test_func)
  test_add_data_func_full (testpath, test_data, test_func)
  test_add_func (testpath, test_func)
  test_assert_expected_messages_internal (domain, file, line, func)
  test_bug (bug_uri_snippet)
  test_bug_base (uri_pattern)
  test_expect_message (log_domain, log_level, pattern)
  test_fail ()
  test_failed ()
  test_get_dir (file_type)
  test_incomplete (msg)
  test_log_type_name (log_type)
  test_queue_destroy (destroy_func, destroy_data)
  test_queue_free (gfree_pointer)
  test_rand_double ()
  test_rand_double_range (range_start, range_end)
  test_rand_int ()
  test_rand_int_range (begin, end)
  test_run ()
  test_run_suite (suite)
  test_set_nonfatal_assertions ()
  test_skip (msg)
  test_subprocess ()
  test_timer_elapsed ()
  test_timer_last ()
  test_timer_start ()
  test_trap_assertions (domain, file, line, func, assertion_flags, pattern)
  test_trap_fork (usec_timeout, test_trap_flags)
  test_trap_has_passed ()
  test_trap_reached_timeout ()
  test_trap_subprocess (test_path, usec_timeout, test_flags)
  thread_error_quark ()
  thread_exit (retval)
  thread_pool_get_max_idle_time ()
  thread_pool_get_max_unused_threads ()
  thread_pool_get_num_unused_threads ()
  thread_pool_set_max_idle_time (interval)
  thread_pool_set_max_unused_threads (max_threads)
  thread_pool_stop_unused_threads ()
  thread_self ()
  thread_yield ()
  threads_init ()
  time_val_from_iso8601 (iso_date)
  timeout_add (priority, interval, function, *data)
  timeout_add_seconds (priority, interval, function, *data)
  timeout_source_new (interval)
  timeout_source_new_seconds (interval)
  trash_stack_height (stack_p)
  trash_stack_peek (stack_p)
  trash_stack_pop (stack_p)
  trash_stack_push (stack_p, data_p)
  try_malloc (n_bytes)
  try_malloc0 (n_bytes)
  try_malloc0_n (n_blocks, n_block_bytes)
  try_malloc_n (n_blocks, n_block_bytes)
  try_realloc (mem, n_bytes)
  try_realloc_n (mem, n_blocks, n_block_bytes)
  ucs4_to_utf16 (str, len)
  ucs4_to_utf8 (str, len)
  unichar_break_type (c)
  unichar_combining_class (uc)
  unichar_compose (a, b, ch)
  unichar_decompose (ch, a, b)
  unichar_digit_value (c)
  unichar_fully_decompose (ch, compat, result, result_len)
  unichar_get_mirror_char (ch, mirrored_ch)
  unichar_get_script (ch)
  unichar_isalnum (c)
  unichar_isalpha (c)
  unichar_iscntrl (c)
  unichar_isdefined (c)
  unichar_isdigit (c)
  unichar_isgraph (c)
  unichar_islower (c)
  unichar_ismark (c)
  unichar_isprint (c)
  unichar_ispunct (c)
  unichar_isspace (c)
  unichar_istitle (c)
  unichar_isupper (c)
  unichar_iswide (c)
  unichar_iswide_cjk (c)
  unichar_isxdigit (c)
  unichar_iszerowidth (c)
  unichar_to_utf8 (c)
  unichar_tolower (c)
  unichar_totitle (c)
  unichar_toupper (c)
  unichar_type (c)
  unichar_validate (ch)
  unichar_xdigit_value (c)
  unicode_canonical_decomposition (ch, result_len)
  unicode_canonical_ordering (string, len)
  unicode_script_from_iso15924 (iso15924)
  unicode_script_to_iso15924 (script)
  unix_error_quark ()
  unix_fd_add_full (priority, fd, condition, function, *user_data)
  unix_fd_source_new (fd, condition)
  unix_open_pipe (fds, flags)
  unix_set_fd_nonblocking (fd, nonblock)
  unix_signal_add (priority, signum, handler, *user_data)
  unix_signal_add_full (*args)
  unix_signal_source_new (signum)
  unlink (filename)
  unsetenv (variable)
  uri_escape_string (unescaped, reserved_chars_allowed, allow_utf8)
  uri_list_extract_uris (uri_list)
  uri_parse_scheme (uri)
  uri_unescape_segment (escaped_string, escaped_string_end, illegal_characters)
  uri_unescape_string (escaped_string, illegal_characters)
  usleep (microseconds)
  utf16_to_ucs4 (str, len)
  utf16_to_utf8 (str, len)
  utf8_casefold (str, len)
  utf8_collate (str1, str2)
  utf8_collate_key (str, len)
  utf8_collate_key_for_filename (str, len)
  utf8_find_next_char (p, end)
  utf8_find_prev_char (str, p)
  utf8_get_char (p)
  utf8_get_char_validated (p, max_len)
  utf8_make_valid (str, len)
  utf8_normalize (str, len, mode)
  utf8_offset_to_pointer (str, offset)
  utf8_pointer_to_offset (str, pos)
  utf8_prev_char (p)
  utf8_strchr (p, len, c)
  utf8_strdown (str, len)
  utf8_strlen (p, max)
  utf8_strncpy (dest, src, n)
  utf8_strrchr (p, len, c)
  utf8_strreverse (str, len)
  utf8_strup (str, len)
  utf8_substring (str, start_pos, end_pos)
  utf8_to_ucs4 (str, len)
  utf8_to_ucs4_fast (str, len)
  utf8_to_utf16 (str, len)
  utf8_validate (str)
  uuid_string_is_valid (str)
  uuid_string_random ()
  variant_get_gtype ()
  variant_is_object_path (string)
  variant_is_signature (string)
  variant_parse (type, text, limit, endptr)
  variant_parse_error_print_context (error, source_str)
  variant_parse_error_quark ()
  variant_parser_get_error_quark ()
  variant_type_checked_ (arg0)
  variant_type_string_is_valid (type_string)
  variant_type_string_scan (string, limit)

Details

GLib.access(filename, mode)[source]
Parameters:
  • filename (str) – a pathname in the GLib file name encoding (UTF-8 on Windows)
  • mode (int) – 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.

Return type:

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().

New in version 2.8.

GLib.ascii_digit_value(c)[source]
Parameters:c (int) – an ASCII character
Returns:If c is a decimal digit (according to g_ascii_isdigit()), its numeric value. Otherwise, -1.
Return type:int

Determines the numeric value of a character as a decimal digit. Differs from GLib.unichar_digit_value() because it takes a str, so there’s no worry about sign extension if characters are signed.

GLib.ascii_dtostr(buffer, buf_len, d)[source]
Parameters:
  • buffer (str) – A buffer to place the resulting string in
  • buf_len (int) – The length of the buffer.
  • d (float) – The float to convert
Returns:

The pointer to the buffer with the converted string.

Return type:

str

Converts a float to a string, using the ‘.’ as decimal point.

This function generates enough precision that converting the string back using GLib.ascii_strtod() gives the same machine-number (on machines with IEEE compatible 64bit doubles). It is guaranteed that the size of the resulting string will never be larger than GLib.ASCII_DTOSTR_BUF_SIZE bytes, including the terminating nul character, which is always added.

GLib.ascii_formatd(buffer, buf_len, format, d)[source]
Parameters:
  • buffer (str) – A buffer to place the resulting string in
  • buf_len (int) – The length of the buffer.
  • format (str) – The printf()-style format to use for the code to use for converting.
  • d (float) – The float to convert
Returns:

The pointer to the buffer with the converted string.

Return type:

str

Converts a float to a string, using the ‘.’ as decimal point. To format the number you pass in a printf()-style format string. Allowed conversion specifiers are ‘e’, ‘E’, ‘f’, ‘F’, ‘g’ and ‘G’.

The returned buffer is guaranteed to be nul-terminated.

If you just want to want to serialize the value into a string, use GLib.ascii_dtostr().

GLib.ascii_strcasecmp(s1, s2)[source]
Parameters:
  • s1 (str) – string to compare with s2
  • s2 (str) – string to compare with s1
Returns:

0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

Return type:

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 s1 and s2 must be non-None.

GLib.ascii_strdown(str, len)[source]
Parameters:
  • str (str) – a string
  • len (int) – length of str in bytes, or -1 if str is nul-terminated
Returns:

a newly-allocated string, with all the upper case characters in str converted to lower case, with semantics that exactly match GLib.ascii_tolower(). (Note that this is unlike the old GLib.strdown(), which modified the string in place.)

Return type:

str

Converts all upper case ASCII letters to lower case ASCII letters.

GLib.ascii_string_to_signed(str, base, min, max)[source]
Parameters:
  • str (str) – a string
  • base (int) – base of a parsed number
  • min (int) – a lower bound (inclusive)
  • max (int) – an upper bound (inclusive)
Raises:

GLib.Error

Returns:

True if str was a number, otherwise False.

out_num:a return location for a number

Return type:

(bool, out_num: int)

A convenience function for converting a string to a signed number.

This function assumes that str contains only a number of the given base that is within inclusive bounds limited by min and max. If this is true, then the converted number is stored in out_num. An empty string is not a valid input. A string with leading or trailing whitespace is also an invalid input.

base can be between 2 and 36 inclusive. Hexadecimal numbers must not be prefixed with “0x” or “0X”. Such a problem does not exist for octal numbers, since they were usually prefixed with a zero which does not change the value of the parsed number.

Parsing failures result in an error with the %G_NUMBER_PARSER_ERROR domain. If the input is invalid, the error code will be GLib.NumberParserError.INVALID. If the parsed number is out of bounds - GLib.NumberParserError.OUT_OF_BOUNDS.

See GLib.ascii_strtoll() if you have more complex needs such as parsing a string which starts with a number, but then has other characters.

New in version 2.54.

GLib.ascii_string_to_unsigned(str, base, min, max)[source]
Parameters:
  • str (str) – a string
  • base (int) – base of a parsed number
  • min (int) – a lower bound (inclusive)
  • max (int) – an upper bound (inclusive)
Raises:

GLib.Error

Returns:

True if str was a number, otherwise False.

out_num:a return location for a number

Return type:

(bool, out_num: int)

A convenience function for converting a string to an unsigned number.

This function assumes that str contains only a number of the given base that is within inclusive bounds limited by min and max. If this is true, then the converted number is stored in out_num. An empty string is not a valid input. A string with leading or trailing whitespace is also an invalid input.

base can be between 2 and 36 inclusive. Hexadecimal numbers must not be prefixed with “0x” or “0X”. Such a problem does not exist for octal numbers, since they were usually prefixed with a zero which does not change the value of the parsed number.

Parsing failures result in an error with the %G_NUMBER_PARSER_ERROR domain. If the input is invalid, the error code will be GLib.NumberParserError.INVALID. If the parsed number is out of bounds - GLib.NumberParserError.OUT_OF_BOUNDS.

See GLib.ascii_strtoull() if you have more complex needs such as parsing a string which starts with a number, but then has other characters.

New in version 2.54.

GLib.ascii_strncasecmp(s1, s2, n)[source]
Parameters:
  • s1 (str) – string to compare with s2
  • s2 (str) – string to compare with s1
  • n (int) – number of characters to compare
Returns:

0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

Return type:

int

Compare s1 and s2, ignoring the case of ASCII characters and any characters after the first n in each string.

Unlike the BSD strcasecmp() 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 GLib.ascii_strcasecmp() applies: Use this function only on strings known to be in encodings where bytes corresponding to ASCII letters always represent themselves.

GLib.ascii_strtod(nptr)[source]
Parameters:nptr (str) – the string to convert to a numeric value.
Returns:the float value.
endptr:if non-None, it returns the character after the last character used in the conversion.
Return type:(float, endptr: str)

Converts a string to a float 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 float to a string in a locale-insensitive way, use GLib.ascii_dtostr().

If the correct value would cause overflow, plus or minus %HUGE_VAL is returned (according to the sign of the value), and %ERANGE is stored in %errno. If the correct value would cause underflow, zero is returned and %ERANGE is stored in %errno.

This function resets %errno before calling strtod() so that you can reliably detect overflow and underflow.

GLib.ascii_strtoll(nptr, base)[source]
Parameters:
  • nptr (str) – the string to convert to a numeric value.
  • base (int) – to be used for the conversion, 2..36 or 0
Returns:

the #gint64 value or zero on error.

endptr:if non-None, it returns the character after the last character used in the conversion.

Return type:

(int, endptr: str)

Converts a string to a #gint64 value. This function behaves like the standard strtoll() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtoll() function.

If the correct value would cause overflow, GLib.MAXINT64 or GLib.MININT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-None).

New in version 2.12.

GLib.ascii_strtoull(nptr, base)[source]
Parameters:
  • nptr (str) – the string to convert to a numeric value.
  • base (int) – to be used for the conversion, 2..36 or 0
Returns:

the #guint64 value or zero on error.

endptr:if non-None, it returns the character after the last character used in the conversion.

Return type:

(int, endptr: str)

Converts a string to a #guint64 value. This function behaves like the standard strtoull() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

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, GLib.MAXUINT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-None).

New in version 2.2.

GLib.ascii_strup(str, len)[source]
Parameters:
  • str (str) – a string
  • len (int) – length of str in bytes, or -1 if str is nul-terminated
Returns:

a newly allocated string, with all the lower case characters in str converted to upper case, with semantics that exactly match GLib.ascii_toupper(). (Note that this is unlike the old GLib.strup(), which modified the string in place.)

Return type:

str

Converts all lower case ASCII letters to upper case ASCII letters.

GLib.ascii_tolower(c)[source]
Parameters:c (int) – any character
Returns:the result of converting c to lower case. If c is not an ASCII upper case letter, c is returned unchanged.
Return type:int

Convert a character to ASCII lower case.

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 str, not an int, so don’t call it on %EOF but no need to worry about casting to #guchar before passing a possibly non-ASCII character in.

GLib.ascii_toupper(c)[source]
Parameters:c (int) – any character
Returns:the result of converting c to upper case. If c is not an ASCII lower case letter, c is returned unchanged.
Return type:int

Convert a character to ASCII upper case.

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 str, not an int, so don’t call it on %EOF but no need to worry about casting to #guchar before passing a possibly non-ASCII character in.

GLib.ascii_xdigit_value(c)[source]
Parameters:c (int) – an ASCII character.
Returns:If c is a hex digit (according to g_ascii_isxdigit()), its numeric value. Otherwise, -1.
Return type:int

Determines the numeric value of a character as a hexidecimal digit. Differs from GLib.unichar_xdigit_value() because it takes a str, so there’s no worry about sign extension if characters are signed.

GLib.assert_warning(log_domain, file, line, pretty_function, expression)[source]
Parameters:
  • log_domain (str) –
  • file (str) –
  • line (int) –
  • pretty_function (str) –
  • expression (str) –
GLib.assertion_message(domain, file, line, func, message)[source]
Parameters:
  • domain (str) –
  • file (str) –
  • line (int) –
  • func (str) –
  • message (str) –
GLib.assertion_message_cmpstr(domain, file, line, func, expr, arg1, cmp, arg2)[source]
Parameters:
  • domain (str) –
  • file (str) –
  • line (int) –
  • func (str) –
  • expr (str) –
  • arg1 (str) –
  • cmp (str) –
  • arg2 (str) –
GLib.assertion_message_error(domain, file, line, func, expr, error, error_domain, error_code)[source]
Parameters:
GLib.atexit(func)[source]
Parameters:func (GLib.VoidFunc) – the function to call on normal program termination.

Specifies a function to be called at normal program termination.

Since GLib 2.8.2, on Windows GLib.atexit() actually is a preprocessor macro that maps to a call to the atexit() function in the C library. This means that in case the code that calls GLib.atexit(), i.e. atexit(), is in a DLL, the function will be called when the DLL is detached from the program. This typically makes more sense than that the function is called when the GLib DLL is detached, which happened earlier when GLib.atexit() was a function in the GLib DLL.

The behaviour of atexit() in the context of dynamically loaded modules is not formally specified and varies wildly.

On POSIX systems, calling GLib.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 GLib.atexit() (or atexit()) except in the main executable of a program.

Deprecated since version 2.32: It is best to avoid GLib.atexit().

GLib.atomic_int_add(atomic, val)[source]
Parameters:
  • atomic (int) – a pointer to a int or int
  • val (int) – the value to add
Returns:

the value of atomic before the add, signed

Return type:

int

Atomically adds val to the value of atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic += val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

Before version 2.30, this function did not return a value (but GLib.atomic_int_exchange_and_add() did, and had the same meaning).

New in version 2.4.

GLib.atomic_int_and(atomic, val)[source]
Parameters:
  • atomic (int) – a pointer to a int or int
  • val (int) – the value to ‘and’
Returns:

the value of atomic before the operation, unsigned

Return type:

int

Performs an atomic bitwise ‘and’ of the value of atomic and val, storing the result back in atomic.

This call acts as a full compiler and hardware memory barrier.

Think of this operation as an atomic version of { tmp = *atomic; *atomic &= val; return tmp; }.

New in version 2.30.

GLib.atomic_int_compare_and_exchange(atomic, oldval, newval)[source]
Parameters:
  • atomic (int) – a pointer to a int or int
  • oldval (int) – the value to compare with
  • newval (int) – the value to conditionally replace with
Returns:

True if the exchange took place

Return type:

bool

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.4.

GLib.atomic_int_dec_and_test(atomic)[source]
Parameters:atomic (int) – a pointer to a int or int
Returns:True if the resultant value is zero
Return type:bool

Decrements the value of atomic by 1.

Think of this operation as an atomic version of { *atomic -= 1; return (*atomic == 0); }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.4.

GLib.atomic_int_exchange_and_add(atomic, val)[source]
Parameters:
  • atomic (int) – a pointer to a int
  • val (int) – the value to add
Returns:

the value of atomic before the add, signed

Return type:

int

This function existed before GLib.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.

New in version 2.4.

Deprecated since version 2.30: Use GLib.atomic_int_add() instead.

GLib.atomic_int_get(atomic)[source]
Parameters:atomic (int) – a pointer to a int or int
Returns:the value of the integer
Return type:int

Gets the current value of atomic.

This call acts as a full compiler and hardware memory barrier (before the get).

New in version 2.4.

GLib.atomic_int_inc(atomic)[source]
Parameters:atomic (int) – a pointer to a int or int

Increments the value of atomic by 1.

Think of this operation as an atomic version of { *atomic += 1; }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.4.

GLib.atomic_int_or(atomic, val)[source]
Parameters:
  • atomic (int) – a pointer to a int or int
  • val (int) – the value to ‘or’
Returns:

the value of atomic before the operation, unsigned

Return type:

int

Performs an atomic bitwise ‘or’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic |= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.30.

GLib.atomic_int_set(atomic, newval)[source]
Parameters:
  • atomic (int) – a pointer to a int or int
  • newval (int) – a new value to store

Sets the value of atomic to newval.

This call acts as a full compiler and hardware memory barrier (after the set).

New in version 2.4.

GLib.atomic_int_xor(atomic, val)[source]
Parameters:
  • atomic (int) – a pointer to a int or int
  • val (int) – the value to ‘xor’
Returns:

the value of atomic before the operation, unsigned

Return type:

int

Performs an atomic bitwise ‘xor’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic ^= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.30.

GLib.atomic_pointer_add(atomic, val)[source]
Parameters:
  • atomic (object) – a pointer to a object-sized value
  • val (int) – the value to add
Returns:

the value of atomic before the add, signed

Return type:

int

Atomically adds val to the value of atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic += val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.30.

GLib.atomic_pointer_and(atomic, val)[source]
Parameters:
  • atomic (object) – a pointer to a object-sized value
  • val (int) – the value to ‘and’
Returns:

the value of atomic before the operation, unsigned

Return type:

int

Performs an atomic bitwise ‘and’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic &= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.30.

GLib.atomic_pointer_compare_and_exchange(atomic, oldval, newval)[source]
Parameters:
  • atomic (object) – a pointer to a object-sized value
  • oldval (object or None) – the value to compare with
  • newval (object or None) – the value to conditionally replace with
Returns:

True if the exchange took place

Return type:

bool

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.4.

GLib.atomic_pointer_get(atomic)[source]
Parameters:atomic (object) – a pointer to a object-sized value
Returns:the value of the pointer
Return type:object or None

Gets the current value of atomic.

This call acts as a full compiler and hardware memory barrier (before the get).

New in version 2.4.

GLib.atomic_pointer_or(atomic, val)[source]
Parameters:
  • atomic (object) – a pointer to a object-sized value
  • val (int) – the value to ‘or’
Returns:

the value of atomic before the operation, unsigned

Return type:

int

Performs an atomic bitwise ‘or’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic |= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.30.

GLib.atomic_pointer_set(atomic, newval)[source]
Parameters:

Sets the value of atomic to newval.

This call acts as a full compiler and hardware memory barrier (after the set).

New in version 2.4.

GLib.atomic_pointer_xor(atomic, val)[source]
Parameters:
  • atomic (object) – a pointer to a object-sized value
  • val (int) – the value to ‘xor’
Returns:

the value of atomic before the operation, unsigned

Return type:

int

Performs an atomic bitwise ‘xor’ of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic ^= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

New in version 2.30.

GLib.atomic_rc_box_acquire(mem_block)[source]
Parameters:mem_block (object) – a pointer to reference counted data
Returns:a pointer to the data, with its reference count increased
Return type:object

Atomically acquires a reference on the data pointed by mem_block.

New in version 2.58.

GLib.atomic_rc_box_alloc(block_size)[source]
Parameters:block_size (int) – the size of the allocation, must be greater than 0
Returns:a pointer to the allocated memory
Return type:object

Allocates block_size bytes of memory, and adds atomic reference counting semantics to it.

The data will be freed when its reference count drops to zero.

New in version 2.58.

GLib.atomic_rc_box_alloc0(block_size)[source]
Parameters:block_size (int) – the size of the allocation, must be greater than 0
Returns:a pointer to the allocated memory
Return type:object

Allocates block_size bytes of memory, and adds atomic referenc 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.

New in version 2.58.

GLib.atomic_rc_box_dup(block_size, mem_block)[source]
Parameters:
  • block_size (int) – the number of bytes to copy, must be greater than 0
  • mem_block (object) – the memory to copy
Returns:

a pointer to the allocated memory

Return type:

object

Allocates a new block of data with atomit reference counting semantics, and copies block_size bytes of mem_block into it.

New in version 2.58.

GLib.atomic_rc_box_get_size(mem_block)[source]
Parameters:mem_block (object) – a pointer to reference counted data
Returns:the size of the data, in bytes
Return type:int

Retrieves the size of the reference counted data pointed by mem_block.

New in version 2.58.

GLib.atomic_rc_box_release(mem_block)[source]
Parameters:mem_block (object) – a pointer to reference counted data

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.

New in version 2.58.

GLib.atomic_rc_box_release_full(mem_block, clear_func)[source]
Parameters:
  • mem_block (object) – a pointer to reference counted data
  • clear_func (GLib.DestroyNotify) – a function to call when clearing the data

Atomically releases a reference on the data pointed by mem_block.

If the reference was the last one, it will call clear_func to clear the contents of mem_block, and then will free the resources allocated for mem_block.

New in version 2.58.

GLib.base64_decode(text)[source]
Parameters:text (str) – zero-terminated string with base64 text to decode
Returns:newly allocated buffer containing the binary data that text represents. The returned buffer must be freed with GLib.free().
Return type:bytes

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.

New in version 2.12.

GLib.base64_decode_inplace(text)[source]
Parameters:text (bytes) – zero-terminated string with base64 text to decode
Returns:The binary data that text responds. This pointer is the same as the input text.
text:zero-terminated string with base64 text to decode
Return type:(int, text: bytes)

Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.

New in version 2.20.

GLib.base64_encode(data)[source]
Parameters:data (bytes) – the binary data to encode
Returns:a newly allocated, zero-terminated Base-64 encoded string representing data. The returned string must be freed with GLib.free().
Return type:str

Encode a sequence of binary data into its Base-64 stringified representation.

New in version 2.12.

GLib.base64_encode_close(break_lines, state, save)[source]
Parameters:
Returns:

The number of bytes of output that was written

out:pointer to destination buffer
state:Saved state from GLib.base64_encode_step()
save:Saved state from GLib.base64_encode_step()

Return type:

(int, out: bytes, state: int, save: int)

Flush the status from a sequence of calls to GLib.base64_encode_step().

The output buffer must be large enough to fit all the data that will be written to it. It will need up to 4 bytes, or up to 5 bytes if line-breaking is enabled.

The out array will not be automatically nul-terminated.

New in version 2.12.

GLib.base64_encode_step(in_, break_lines, state, save)[source]
Parameters:
  • in (bytes) – the binary data to encode
  • break_lines (bool) – whether to break long lines
  • state (int) – Saved state between steps, initialize to 0
  • save (int) – Saved state between steps, initialize to 0
Returns:

The number of bytes of output that was written

out:pointer to destination buffer
state:Saved state between steps, initialize to 0
save:Saved state between steps, initialize to 0

Return type:

(int, out: bytes, state: int, save: 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 GLib.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) / 72 + 1 bytes of extra space.

break_lines is typically used when putting base64-encoded data in emails. It breaks the lines at 72 columns instead of putting all of the text on the same line. This avoids problems with long lines in the email system. Note however that it breaks the lines with LF characters, not CR LF sequences, so the result cannot be passed directly to SMTP or certain other protocols.

New in version 2.12.

GLib.basename(file_name)[source]
Parameters:file_name (str) – the name of the file
Returns:the name of the file without any leading directory components
Return type: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 GLib.path_get_basename() instead, but notice that GLib.path_get_basename() allocates new memory for the returned string, unlike this function which returns a pointer into the argument.

GLib.bit_lock(address, lock_bit)[source]
Parameters:
  • address (int) – a pointer to an integer
  • lock_bit (int) – a bit value between 0 and 31

Sets the indicated lock_bit in address. If the bit is already set, this call will block until GLib.bit_unlock() unsets the corresponding bit.

Attempting to lock on two different bits within the same integer is not supported and will very probably cause deadlocks.

The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably.

New in version 2.24.

GLib.bit_nth_lsf(mask, nth_bit)[source]
Parameters:
  • mask (int) – a int containing flags
  • nth_bit (int) – 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

Return type:

int

Find the position of the first bit set in mask, searching from (but not including) nth_bit upwards. Bits are numbered from 0 (least significant) to sizeof(int) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, set nth_bit to -1.

GLib.bit_nth_msf(mask, nth_bit)[source]
Parameters:
  • mask (int) – a int containing flags
  • nth_bit (int) – 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

Return type:

int

Find the position of the first bit set in mask, searching from (but not including) nth_bit downwards. Bits are numbered from 0 (least significant) to sizeof(int) * 8 - 1 (31 or 63, usually). To start searching from the last bit, set nth_bit to -1 or GLib.SIZEOF_LONG * 8.

GLib.bit_storage(number)[source]
Parameters:number (int) – a int
Returns:the number of bits used to hold number
Return type:int

Gets the number of bits used to hold number, e.g. if number is 4, 3 bits are needed.

GLib.bit_trylock(address, lock_bit)[source]
Parameters:
  • address (int) – a pointer to an integer
  • lock_bit (int) – a bit value between 0 and 31
Returns:

True if the lock was acquired

Return type:

bool

Sets the indicated lock_bit in address, returning True if successful. If the bit is already set, returns False immediately.

Attempting to lock on two different bits within the same integer is not supported.

The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably.

New in version 2.24.

GLib.bit_unlock(address, lock_bit)[source]
Parameters:
  • address (int) – a pointer to an integer
  • lock_bit (int) – a bit value between 0 and 31

Clears the indicated lock_bit in address. If another thread is currently blocked in GLib.bit_lock() on this same bit then it will be woken up.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably.

New in version 2.24.

GLib.bookmark_file_error_quark()[source]
Return type:int
GLib.build_filenamev(args)[source]
Parameters:args ([str]) – None-terminated array of strings containing the path elements.
Returns:a newly-allocated string that must be freed with GLib.free().
Return type:str

Behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

New in version 2.8.

GLib.build_pathv(separator, args)[source]
Parameters:
  • separator (str) – a string used to separator the elements of the path.
  • args ([str]) – None-terminated array of strings containing the path elements.
Returns:

a newly-allocated string that must be freed with GLib.free().

Return type:

str

Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

New in version 2.8.

GLib.byte_array_free(array, free_segment)[source]
Parameters:
Returns:

the element data if free_segment is False, otherwise None. The element data should be freed using GLib.free().

Return type:

int

Frees the memory allocated by the GLib.ByteArray. If free_segment is True it frees the actual byte data. If the reference count of array is greater than one, the GLib.ByteArray wrapper is preserved but the size of array will be set to zero.

GLib.byte_array_free_to_bytes(array)[source]
Parameters:array (bytes) – a GLib.ByteArray
Returns:a new immutable GLib.Bytes representing same byte data that was in the array
Return type:GLib.Bytes

Transfers the data from the GLib.ByteArray into a new immutable GLib.Bytes.

The GLib.ByteArray is freed unless the reference count of array is greater than one, the GLib.ByteArray wrapper is preserved but the size of array will be set to zero.

This is identical to using GLib.Bytes.new_take() and GLib.ByteArray.free() together.

New in version 2.32.

GLib.byte_array_new()[source]
Returns:the new GLib.ByteArray
Return type:bytes

Creates a new GLib.ByteArray with a reference count of 1.

GLib.byte_array_new_take(data)[source]
Parameters:data (bytes) – byte data for the array
Returns:a new GLib.ByteArray
Return type:bytes

Create byte array containing the data. The data will be owned by the array and will be freed with GLib.free(), i.e. it could be allocated using GLib.strdup().

New in version 2.32.

GLib.byte_array_unref(array)[source]
Parameters:array (bytes) – A GLib.ByteArray

Atomically decrements the reference count of array by one. If the reference count drops to 0, all memory allocated by the array is released. This function is thread-safe and may be called from any thread.

New in version 2.22.

GLib.canonicalize_filename(filename, relative_to)[source]
Parameters:
  • filename (str) – the name of the file
  • relative_to (str or None) – the relative directory, or None to use the current working directory
Returns:

a newly allocated string with the canonical file path

Return type:

str

Gets the canonical file name from filename. All triple slashes are turned into single slashes, and all .. and ``.``s resolved against relative_to.

Symlinks are not followed, and the returned path is guaranteed to be absolute.

If filename is an absolute path, relative_to is ignored. Otherwise, relative_to will be prepended to filename to make it absolute. relative_to must be an absolute path, or None. If relative_to is None, it’ll fallback to GLib.get_current_dir().

This function never fails, and will canonicalize file paths even if they don’t exist.

No file system I/O is done.

New in version 2.58.

GLib.chdir(path)[source]
Parameters:path (str) – a pathname in the GLib file name encoding (UTF-8 on Windows)
Returns:0 on success, -1 if an error occurred.
Return type: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().

New in version 2.8.

GLib.check_version(required_major, required_minor, required_micro)[source]
Parameters:
  • required_major (int) – the required major version
  • required_minor (int) – the required minor version
  • required_micro (int) – the required micro version
Returns:

None if 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.

Return type:

str

Checks that the GLib library in use is compatible with the given version. Generally you would pass in the constants GLib.MAJOR_VERSION, GLib.MINOR_VERSION, GLib.MICRO_VERSION as the three arguments to this function; that produces a check that the library in use is compatible with the version of GLib the application or module was compiled against.

Compatibility is defined by two things: first the version of the running library is newer than the version required_major.required_minor.`required_micro`. Second the running library must be binary compatible with the version required_major.required_minor.`required_micro` (same major version.)

New in version 2.6.

GLib.checksum_type_get_length(checksum_type)[source]
Parameters:checksum_type (GLib.ChecksumType) – a GLib.ChecksumType
Returns:the checksum length, or -1 if checksum_type is not supported.
Return type:int

Gets the length in bytes of digests of type checksum_type

New in version 2.16.

GLib.child_watch_add(priority, pid, function, *data)[source]
Parameters:
  • priority – the priority of the idle source. Typically this will be in the range between GLib.PRIORITY_DEFAULT_IDLE and GLib.PRIORITY_HIGH_IDLE.
  • 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).
  • function – function to call
  • data – data to pass to function

Sets a function to be called when the child indicated by pid exits, at the priority priority.

If you obtain pid from GLib.spawn_async() or GLib.spawn_async_with_pipes() you will need to pass GLib.SpawnFlags.DO_NOT_REAP_CHILD as flag to the spawn function for the child watching to work.

In many programs, you will want to call GLib.spawn_check_exit_status() in the callback to determine whether or not the child exited successfully.

Also, note that on platforms where #GPid must be explicitly closed (see GLib.spawn_close_pid()) pid must not be closed while the source is still active. Typically, you should invoke GLib.spawn_close_pid() in the callback function for the source.

GLib supports only a single callback per process id. On POSIX platforms, the same restrictions mentioned for GLib.child_watch_source_new() apply to this function.

This internally creates a main loop source using GLib.child_watch_source_new() and attaches it to the main loop context using GLib.Source.attach(). You can do these steps manually if you need greater control.

New in version 2.4.

GLib.child_watch_source_new(pid)[source]
Parameters:pid (int) – 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
Return type:GLib.Source

Creates a new child_watch source.

The source will not initially be associated with any GLib.MainContext and must be added to one with GLib.Source.attach() before it will be executed.

Note that child watch sources can only be used in conjunction with g_spawn... when the GLib.SpawnFlags.DO_NOT_REAP_CHILD flag is used.

Note that on platforms where #GPid must be explicitly closed (see GLib.spawn_close_pid()) pid must not be closed while the source is still active. Typically, you will want to call GLib.spawn_close_pid() in the callback function for the source.

On POSIX platforms, the following restrictions apply to this API due to limitations in POSIX process interfaces:

  • pid must be a child of this process
  • pid must be positive
  • the application must not call waitpid with a non-positive first argument, for instance in another thread
  • the application must not wait for pid to exit by any other mechanism, including waitpid(pid, ...) or a second child-watch source for the same pid
  • the application must not ignore SIGCHILD

If any of those conditions are not met, this and related APIs will not work correctly. This can often be diagnosed via a GLib warning stating that ECHILD was received by waitpid.

Calling waitpid for specific processes other than pid remains a valid thing to do.

New in version 2.4.

GLib.clear_error()[source]
Raises:GLib.Error

If err or err is None, does nothing. Otherwise, calls GLib.Error.free() on err and sets err to None.

GLib.close(fd)[source]
Parameters:fd (int) – A file descriptor
Raises:GLib.Error
Returns:True on success, False if there was an error.
Return type:bool

This wraps the close() call; in case of error, %errno will be preserved, but the error will also be stored as a GLib.Error in error.

Besides using GLib.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.

New in version 2.36.

GLib.compute_checksum_for_bytes(checksum_type, data)[source]
Parameters:
Returns:

the digest of the binary data as a string in hexadecimal. The returned string should be freed with GLib.free() when done using it.

Return type:

str

Computes the checksum for a binary data. This is a convenience wrapper for GLib.Checksum.new(), GLib.Checksum.get_string() and GLib.Checksum.free().

The hexadecimal string returned will be in lower case.

New in version 2.34.

GLib.compute_checksum_for_data(checksum_type, data)[source]
Parameters:
Returns:

the digest of the binary data as a string in hexadecimal. The returned string should be freed with GLib.free() when done using it.

Return type:

str

Computes the checksum for a binary data of length. This is a convenience wrapper for GLib.Checksum.new(), GLib.Checksum.get_string() and GLib.Checksum.free().

The hexadecimal string returned will be in lower case.

New in version 2.16.

GLib.compute_checksum_for_string(checksum_type, str, length)[source]
Parameters:
Returns:

the checksum as a hexadecimal string. The returned string should be freed with GLib.free() when done using it.

Return type:

str

Computes the checksum of a string.

The hexadecimal string returned will be in lower case.

New in version 2.16.

GLib.compute_hmac_for_bytes(digest_type, key, data)[source]
Parameters:
Returns:

the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with GLib.free() when done using it.

Return type:

str

Computes the HMAC for a binary data. This is a convenience wrapper for g_hmac_new(), GLib.Hmac.get_string() and GLib.Hmac.unref().

The hexadecimal string returned will be in lower case.

New in version 2.50.

GLib.compute_hmac_for_data(digest_type, key, data)[source]
Parameters:
Returns:

the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with GLib.free() when done using it.

Return type:

str

Computes the HMAC for a binary data of length. This is a convenience wrapper for g_hmac_new(), GLib.Hmac.get_string() and GLib.Hmac.unref().

The hexadecimal string returned will be in lower case.

New in version 2.30.

GLib.compute_hmac_for_string(digest_type, key, str, length)[source]
Parameters:
  • digest_type (GLib.ChecksumType) – a GLib.ChecksumType to use for the HMAC
  • key (bytes) – the key to use in the HMAC
  • str (str) – the string to compute the HMAC for
  • length (int) – 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 GLib.free() when done using it.

Return type:

str

Computes the HMAC for a string.

The hexadecimal string returned will be in lower case.

New in version 2.30.

GLib.convert(str, to_codeset, from_codeset)[source]
Parameters:
  • str (bytes) – the string to convert.
  • to_codeset (str) – name of character set into which to convert str
  • from_codeset (str) – character set of str.
Raises:

GLib.Error

Returns:

If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with GLib.free(). Otherwise None and error will be set.

bytes_read:location to store the number of bytes in the input string that were successfully converted, or None. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error GLib.ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.

Return type:

(bytes, bytes_read: int)

Converts a string from one character set to another.

Note that you should use g_iconv() for streaming conversions. Despite the fact that bytes_read can return information about partial characters, the g_convert_… functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won’t be preserved across successive calls to GLib.convert(), g_convert_with_iconv() or GLib.convert_with_fallback(). (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)

Using extensions such as “//TRANSLIT” may not work (or may not work well) on many platforms. Consider using GLib.str_to_ascii() instead.

GLib.convert_error_quark()[source]
Return type:int
GLib.convert_with_fallback(str, to_codeset, from_codeset, fallback)[source]
Parameters:
  • str (bytes) – the string to convert.
  • to_codeset (str) – name of character set into which to convert str
  • from_codeset (str) – character set of str.
  • fallback (str) – 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.
Raises:

GLib.Error

Returns:

If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with GLib.free(). Otherwise None and error will be set.

bytes_read:location to store the number of bytes in the input string that were successfully converted, or None. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input.

Return type:

(bytes, bytes_read: int)

Converts a string from one character set to another, possibly including fallback sequences for characters not representable in the output. Note that it is not guaranteed that the specification for the fallback sequences in fallback will be honored. Some systems may do an approximate conversion from from_codeset to to_codeset in their iconv() functions, in which case GLib will simply return that approximate conversion.

Note that you should use g_iconv() for streaming conversions. Despite the fact that bytes_read can return information about partial characters, the g_convert_… functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won’t be preserved across successive calls to GLib.convert(), g_convert_with_iconv() or GLib.convert_with_fallback(). (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)

GLib.datalist_foreach(datalist, func, *user_data)[source]
Parameters:

Calls the given function for each data element of the datalist. The function is called with each data element’s #GQuark id and data, together with the given user_data parameter. Note that this function is NOT thread-safe. So unless datalist can be protected from any modifications during invocation of this function, it should not be called.

func can make changes to datalist, but the iteration will not reflect changes made during the GLib.datalist_foreach() call, other than skipping over elements that are removed.

GLib.datalist_get_data(datalist, key)[source]
Parameters:
  • datalist (GLib.Data) – a datalist.
  • key (str) – the string identifying a data element.
Returns:

the data element, or None if it is not found.

Return type:

object or None

Gets a data element, using its string identifier. This is slower than GLib.datalist_id_get_data() because it compares strings.

GLib.datalist_get_flags(datalist)[source]
Parameters:datalist (GLib.Data) – pointer to the location that holds a list
Returns:the flags of the datalist
Return type:int

Gets flags values packed in together with the datalist. See GLib.datalist_set_flags().

New in version 2.8.

GLib.datalist_id_get_data(datalist, key_id)[source]
Parameters:
  • datalist (GLib.Data) – a datalist.
  • key_id (int) – the #GQuark identifying a data element.
Returns:

the data element, or None if it is not found.

Return type:

object or None

Retrieves the data element corresponding to key_id.

GLib.datalist_set_flags(datalist, flags)[source]
Parameters:
  • datalist (GLib.Data) – pointer to the location that holds a list
  • flags (int) – the flags to turn on. The values of the flags are restricted by GLib.DATALIST_FLAGS_MASK (currently 3; giving two possible boolean flags). A value for flags that doesn’t fit within the mask is an error.

Turns on flag values for a data list. This function is used to keep a small number of boolean flags in an object with a data list without using any additional space. It is not generally useful except in circumstances where space is very tight. (It is used in the base #GObject type, for example.)

New in version 2.8.

GLib.datalist_unset_flags(datalist, flags)[source]
Parameters:
  • datalist (GLib.Data) – pointer to the location that holds a list
  • flags (int) – the flags to turn off. The values of the flags are restricted by GLib.DATALIST_FLAGS_MASK (currently 3: giving two possible boolean flags). A value for flags that doesn’t fit within the mask is an error.

Turns off flag values for a data list. See GLib.datalist_unset_flags()

New in version 2.8.

GLib.dataset_destroy(dataset_location)[source]
Parameters:dataset_location (object) – the location identifying the dataset.

Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.

GLib.dataset_foreach(dataset_location, func, *user_data)[source]
Parameters:
  • dataset_location (object) – the location identifying the dataset.
  • func (GLib.DataForeachFunc) – the function to call for each data element.
  • user_data (object or None) – user data to pass to the function.

Calls the given function for each data element which is associated with the given location. Note that this function is NOT thread-safe. So unless dataset_location can be protected from any modifications during invocation of this function, it should not be called.

func can make changes to the dataset, but the iteration will not reflect changes made during the GLib.dataset_foreach() call, other than skipping over elements that are removed.

GLib.dataset_id_get_data(dataset_location, key_id)[source]
Parameters:
  • dataset_location (object) – the location identifying the dataset.
  • key_id (int) – the #GQuark id to identify the data element.
Returns:

the data element corresponding to the #GQuark, or None if it is not found.

Return type:

object or None

Gets the data element corresponding to a #GQuark.

GLib.date_get_days_in_month(month, year)[source]
Parameters:
Returns:

number of days in month during the year

Return type:

int

Returns the number of days in a month, taking leap years into account.

GLib.date_get_monday_weeks_in_year(year)[source]
Parameters:year (int) – a year
Returns:number of Mondays in the year
Return type:int

Returns the number of weeks in the year, where weeks are taken to start on Monday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it’s a leap year. This function is basically telling you how many Mondays are in the year, i.e. there are 53 Mondays if one of the extra days happens to be a Monday.)

GLib.date_get_sunday_weeks_in_year(year)[source]
Parameters:year (int) – year to count weeks in
Returns:the number of weeks in year
Return type:int

Returns the number of weeks in the year, where weeks are taken to start on Sunday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it’s a leap year. This function is basically telling you how many Sundays are in the year, i.e. there are 53 Sundays if one of the extra days happens to be a Sunday.)

GLib.date_is_leap_year(year)[source]
Parameters:year (int) – year to check
Returns:True if the year is a leap year
Return type:bool

Returns True if the year is a leap year.

For the purposes of this function, leap year is every year divisible by 4 unless that year is divisible by 100. If it is divisible by 100 it would be a leap year only if that year is also divisible by 400.

GLib.date_strftime(s, slen, format, date)[source]
Parameters:
Returns:

number of characters written to the buffer, or 0 the buffer was too small

Return type:

int

Generates a printed representation of the date, in a locale-specific way. Works just like the platform’s C library strftime() function, but only accepts date-related formats; time-related formats give undefined results. Date must be valid. Unlike strftime() (which uses the locale encoding), works on a UTF-8 format string and stores a UTF-8 result.

This function does not provide any conversion specifiers in addition to those implemented by the platform’s C library. For example, don’t expect that using GLib.Date.strftime() would make the \%F provided by the C99 strftime() work on Windows where the C library only complies to C89.

GLib.date_time_compare(dt1, dt2)[source]
Parameters:
Returns:

-1, 0 or 1 if dt1 is less than, equal to or greater than dt2.

Return type:

int

A comparison function for GLib.DateTimes that is suitable as a GLib.CompareFunc. Both GLib.DateTimes must be non-None.

New in version 2.26.

GLib.date_time_equal(dt1, dt2)[source]
Parameters:
Returns:

True if dt1 and dt2 are equal

Return type:

bool

Checks to see if dt1 and dt2 are equal.

Equal here means that they represent the same moment after converting them to the same time zone.

New in version 2.26.

GLib.date_time_hash(datetime)[source]
Parameters:datetime (object) – a GLib.DateTime
Returns:a int containing the hash
Return type:int

Hashes datetime into a int, suitable for use within GLib.HashTable.

New in version 2.26.

GLib.date_valid_day(day)[source]
Parameters:day (int) – day to check
Returns:True if the day is valid
Return type:bool

Returns True if the day of the month is valid (a day is valid if it’s between 1 and 31 inclusive).

GLib.date_valid_dmy(day, month, year)[source]
Parameters:
Returns:

True if the date is a valid one

Return type:

bool

Returns True if the day-month-year triplet forms a valid, existing day in the range of days GLib.Date understands (Year 1 or later, no more than a few thousand years in the future).

GLib.date_valid_julian(julian_date)[source]
Parameters:julian_date (int) – Julian day to check
Returns:True if the Julian day is valid
Return type:bool

Returns True if the Julian day is valid. Anything greater than zero is basically a valid Julian, though there is a 32-bit limit.

GLib.date_valid_month(month)[source]
Parameters:month (GLib.DateMonth) – month
Returns:True if the month is valid
Return type:bool

Returns True if the month value is valid. The 12 GLib.DateMonth enumeration values are the only valid months.

GLib.date_valid_weekday(weekday)[source]
Parameters:weekday (GLib.DateWeekday) – weekday
Returns:True if the weekday is valid
Return type:bool

Returns True if the weekday is valid. The seven GLib.DateWeekday enumeration values are the only valid weekdays.

GLib.date_valid_year(year)[source]
Parameters:year (int) – year
Returns:True if the year is valid
Return type:bool

Returns True if the year is valid. Any year greater than 0 is valid, though there is a 16-bit limit to what GLib.Date will understand.

GLib.dcgettext(domain, msgid, category)[source]
Parameters:
  • domain (str or None) – the translation domain to use, or None to use the domain set with textdomain()
  • msgid (str) – message to translate
  • category (int) – a locale category
Returns:

the translated string for the given locale category

Return type:

str

This is a variant of GLib.dgettext() that allows specifying a locale category instead of always using LC_MESSAGES. See GLib.dgettext() for more information about how this functions differs from calling dcgettext() directly.

New in version 2.26.

GLib.dgettext(domain, msgid)[source]
Parameters:
  • domain (str or None) – the translation domain to use, or None to use the domain set with textdomain()
  • msgid (str) – message to translate
Returns:

The translated string

Return type:

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 GLib.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:

  • domain is not None
  • textdomain() has been called to set a default text domain
  • there is no translations available for the default text domain and the current locale
  • current locale is not “C” or any English locales (those starting with “en_”)

Note that this behavior may not be desired for example if an application has its untranslated messages in a language other than English. In those cases the application should call textdomain() after initializing GTK+.

Applications should normally not use this function directly, but use the _() macro for translations.

New in version 2.18.

GLib.dir_make_tmp(tmpl)[source]
Parameters:tmpl (str or None) – Template for directory name, as in g_mkdtemp(), basename only, or None for a default template
Raises:GLib.Error
Returns:The actual name used. This string should be freed with GLib.free() when not needed any longer and is is in the GLib file name encoding. In case of errors, None is returned and error will be set.
Return type:str

Creates a subdirectory in the preferred directory for temporary files (as returned by GLib.get_tmp_dir()).

tmpl should be a string in the GLib file name encoding containing a sequence of six ‘X’ characters, as the parameter to g_mkstemp(). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template is None, a default template is used.

Note that in contrast to g_mkdtemp() (and mkdtemp()) tmpl is not modified, and might thus be a read-only literal string.

New in version 2.30.

GLib.direct_equal(v1, v2)[source]
Parameters:
Returns:

True if the two keys match.

Return type:

bool

Compares two object arguments and returns True if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using opaque pointers compared by pointer value as keys in a GLib.HashTable.

This equality function is also appropriate for keys that are integers stored in pointers, such as GINT_TO_POINTER (n).

GLib.direct_hash(v)[source]
Parameters:v (object or None) – a object key
Returns:a hash value corresponding to the key.
Return type:int

Converts a object to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using opaque pointers compared by pointer value as keys in a GLib.HashTable.

This hash function is also appropriate for keys that are integers stored in pointers, such as GINT_TO_POINTER (n).

GLib.dngettext(domain, msgid, msgid_plural, n)[source]
Parameters:
  • domain (str or None) – the translation domain to use, or None to use the domain set with textdomain()
  • msgid (str) – message to translate
  • msgid_plural (str) – plural form of the message
  • n (int) – the quantity for which translation is needed
Returns:

The translated string

Return type:

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 GLib.dgettext() for details of how this differs from dngettext() proper.

New in version 2.18.

GLib.double_equal(v1, v2)[source]
Parameters:
Returns:

True if the two keys match.

Return type:

bool

Compares the two float values being pointed to and returns True if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-None pointers to doubles as keys in a GLib.HashTable.

New in version 2.22.

GLib.double_hash(v)[source]
Parameters:v (object) – a pointer to a float key
Returns:a hash value corresponding to the key.
Return type:int

Converts a pointer to a float to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, It can be passed to g_hash_table_new() as the hash_func parameter, when using non-None pointers to doubles as keys in a GLib.HashTable.

New in version 2.22.

GLib.dpgettext(domain, msgctxtid, msgidoffset)[source]
Parameters:
  • domain (str or None) – the translation domain to use, or None to use the domain set with textdomain()
  • msgctxtid (str) – a combined message context and message id, separated by a \004 character
  • msgidoffset (int) – the offset of the message id in msgctxid
Returns:

The translated string

Return type:

str

This function is a variant of GLib.dgettext() which supports a disambiguating message context. GNU gettext uses the ‘\004’ character to separate the message context and message id in msgctxtid. If 0 is passed as msgidoffset, this function will fall back to trying to use the deprecated convention of using “|” as a separation character.

This uses GLib.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.

New in version 2.16.

GLib.dpgettext2(domain, context, msgid)[source]
Parameters:
  • domain (str or None) – the translation domain to use, or None to use the domain set with textdomain()
  • context (str) – the message context
  • msgid (str) – the message
Returns:

The translated string

Return type:

str

This function is a variant of GLib.dgettext() which supports a disambiguating message context. GNU gettext uses the ‘\004’ character to separate the message context and message id in msgctxtid.

This uses GLib.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.

New in version 2.18.

GLib.environ_getenv(envp, variable)[source]
Parameters:
  • envp ([str] or None) – an environment list (eg, as returned from GLib.get_environ()), or None for an empty environment list
  • variable (str) – the environment variable to get
Returns:

the value of the environment variable, or None if the environment variable is not set in envp. The returned string is owned by envp, and will be freed if variable is set or unset again.

Return type:

str

Returns the value of the environment variable variable in the provided list envp.

New in version 2.32.

GLib.environ_setenv(envp, variable, value, overwrite)[source]
Parameters:
  • envp ([str] or None) – an environment list that can be freed using GLib.strfreev() (e.g., as returned from GLib.get_environ()), or None for an empty environment list
  • variable (str) – the environment variable to set, must not contain ‘=’
  • value (str) – the value for to set the variable to
  • overwrite (bool) – whether to change the variable if it already exists
Returns:

the updated environment list. Free it using GLib.strfreev().

Return type:

[str]

Sets the environment variable variable in the provided list envp to value.

New in version 2.32.

GLib.environ_unsetenv(envp, variable)[source]
Parameters:
  • envp ([str] or None) – an environment list that can be freed using GLib.strfreev() (e.g., as returned from GLib.get_environ()), or None for an empty environment list
  • variable (str) – the environment variable to remove, must not contain ‘=’
Returns:

the updated environment list. Free it using GLib.strfreev().

Return type:

[str]

Removes the environment variable variable from the provided environment envp.

New in version 2.32.

GLib.file_error_from_errno(err_no)[source]
Parameters:err_no (int) – an “errno” value
Returns:GLib.FileError corresponding to the given errno
Return type:GLib.FileError

Gets a GLib.FileError constant based on the passed-in err_no. For example, if you pass in EEXIST this function returns GLib.FileError.EXIST. Unlike errno values, you can portably assume that all GLib.FileError values will exist.

Normally a GLib.FileError value goes into a GLib.Error returned from a function that manipulates files. So you would use GLib.file_error_from_errno() when constructing a GLib.Error.

GLib.file_error_quark()[source]
Return type:int
GLib.file_get_contents(filename)[source]
Parameters:filename (str) – name of a file to read contents from, in the GLib file name encoding
Raises:GLib.Error
Returns:True on success, False if an error occurred
contents:location to store an allocated string, use GLib.free() to free the returned string
Return type:(bool, contents: bytes)

Reads an entire file into allocated memory, with good error checking.

If the call was successful, it returns True and sets contents to the file contents and length to the length of the file contents in bytes. The string stored in contents will be nul-terminated, so for text files you can pass None for the length argument. If the call was not successful, it returns False and sets error. The error domain is #G_FILE_ERROR. Possible error codes are those in the GLib.FileError enumeration. In the error case, contents is set to None and length is set to zero.

GLib.file_open_tmp(tmpl)[source]
Parameters:tmpl (str or None) – Template for file name, as in g_mkstemp(), basename only, or None for a default template
Raises:GLib.Error
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 error will be set.
name_used:location to store actual name used, or None
Return type:(int, name_used: str)

Opens a file for writing in the preferred directory for temporary files (as returned by GLib.get_tmp_dir()).

tmpl should be a string in the GLib file name encoding containing a sequence of six ‘X’ characters, as the parameter to g_mkstemp(). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template is None, a default template is used.

Note that in contrast to g_mkstemp() (and mkstemp()) tmpl is not modified, and might thus be a read-only literal string.

Upon success, and if name_used is non-None, the actual name used is returned in name_used. This string should be freed with GLib.free() when not needed any longer. The returned name is in the GLib file name encoding.

Parameters:filename (str) – the symbolic link
Raises:GLib.Error
Returns:A newly-allocated string with the contents of the symbolic link, or None if an error occurred.
Return type:str

Reads the contents of the symbolic link filename like the POSIX readlink() function. The returned string is in the encoding used for filenames. Use GLib.filename_to_utf8() to convert it to UTF-8.

New in version 2.4.

GLib.file_set_contents(filename, contents)[source]
Parameters:
  • filename (str) – name of a file to write contents to, in the GLib file name encoding
  • contents (bytes) – string to write to the file
Raises:

GLib.Error

Returns:

True on success, False if an error occurred

Return type:

bool

Writes all of contents to a file named filename, with good error checking. If a file called filename already exists it will be overwritten.

This write 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 filename already exists hard links to filename will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. If filename is a symbolic link, the link itself will be replaced, not the linked file.
  • On UNIX, if filename already exists and is non-empty, and if the system supports it (via a journalling filesystem or equivalent), the fsync() call (or equivalent) will be used to ensure atomic replacement: filename will contain either its old contents or contents, even in the face of system power loss, the disk being unsafely removed, etc.
  • On UNIX, if filename does not already exist or is empty, there is a possibility that system power loss etc. after calling this function will leave filename empty or full of NUL bytes, depending on the underlying filesystem.
  • 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 filename already exists and is open.

If the call was successful, it returns True. If the call was not successful, it returns False and sets error. The error domain is #G_FILE_ERROR. Possible error codes are those in the GLib.FileError enumeration.

Note that the name for the temporary file is constructed by appending up to 7 characters to filename.

New in version 2.8.

GLib.file_test(filename, test)[source]
Parameters:
Returns:

whether a test was True

Return type:

bool

Returns True if any of the tests in the bitfield test are True. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) will return True if the file exists; the check whether it’s a directory doesn’t matter since the existence test is True. With the current set of available tests, there’s no point passing in more than one test at a time.

Apart from GLib.FileTest.IS_SYMLINK all tests follow symbolic links, so for a symbolic link to a regular file GLib.file_test() will return True for both GLib.FileTest.IS_SYMLINK and GLib.FileTest.IS_REGULAR.

Note, that for a dangling symbolic link GLib.file_test() will return True for GLib.FileTest.IS_SYMLINK and False for all other flags.

You should never use GLib.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. For example, you might think you could use GLib.FileTest.IS_SYMLINK to know whether it is safe to write to a file without being tricked into writing into a different location. It doesn’t work!

// DON'T DO THIS
if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
  {
    fd = g_open (filename, O_WRONLY);
    // write to fd
  }

Another thing to note is that GLib.FileTest.EXISTS and GLib.FileTest.IS_EXECUTABLE are implemented using the access() system call. This usually doesn’t matter, but if your program is setuid or setgid it means that these tests will give you the answer for the real user ID and group ID, rather than the effective user ID and group ID.

On Windows, there are no symlinks, so testing for GLib.FileTest.IS_SYMLINK will always return False. Testing for GLib.FileTest.IS_EXECUTABLE will just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in the PATHEXT environment variable.

GLib.filename_display_basename(filename)[source]
Parameters:filename (str) – 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
Return type: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 “\357\277\275” in octal notation) to find out if filename was in an invalid encoding.

You must pass the whole absolute pathname to this functions so that translation of well known locations can be done.

This function is preferred over GLib.filename_display_name() if you know the whole path, as it allows translation.

New in version 2.6.

GLib.filename_display_name(filename)[source]
Parameters:filename (str) – a pathname hopefully in the GLib file name encoding
Returns:a newly allocated string containing a rendition of the filename in valid UTF-8
Return type: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 GLib.filename_to_utf8(), the result is guaranteed to be non-None even if the filename actually isn’t in the GLib file name encoding.

If GLib cannot make sense of the encoding of filename, as a last resort it replaces unknown characters with U+FFFD, the Unicode replacement character. You can search the result for the UTF-8 encoding of this character (which is “\357\277\275” in octal notation) to find out if filename was in an invalid encoding.

If you know the whole pathname of the file you should use GLib.filename_display_basename(), since that allows location-based translation of filenames.

New in version 2.6.

GLib.filename_from_uri(uri)[source]
Parameters:uri (str) – a uri describing a filename (escaped, encoded in ASCII).
Raises:GLib.Error
Returns:a newly-allocated string holding the resulting filename, or None on an error.
hostname:Location to store hostname for the URI. If there is no hostname in the URI, None will be stored in this location.
Return type:(str, hostname: str or None)

Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.

GLib.filename_from_utf8(utf8string, len)[source]
Parameters:
  • utf8string (str) – a UTF-8 encoded string.
  • len (int) – the length of the string, or -1 if the string is nul-terminated.
Raises:

GLib.Error

Returns:

The converted string, or None on an error.

bytes_read:location to store the number of bytes in the input string that were successfully converted, or None. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error GLib.ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
bytes_written:the number of bytes stored in the output buffer (not including the terminating nul).

Return type:

(str, bytes_read: int, bytes_written: int)

Converts a string from UTF-8 to the encoding GLib uses for filenames. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error GLib.ConvertError.ILLEGAL_SEQUENCE. If the filename encoding is not UTF-8 and the conversion output contains a nul character, the error GLib.ConvertError.EMBEDDED_NUL is set and the function returns None.

GLib.filename_to_uri(filename, hostname)[source]
Parameters:
  • filename (str) – 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 (str or None) – A UTF-8 encoded hostname, or None for none.
Raises:

GLib.Error

Returns:

a newly-allocated string holding the resulting URI, or None on an error.

Return type:

str

Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3. of RFC 2396.

GLib.filename_to_utf8(opsysstring, len)[source]
Parameters:
  • opsysstring (str) – a string in the encoding for filenames
  • len (int) – 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 len parameter is unsafe)
Raises:

GLib.Error

Returns:

The converted string, or None on an error.

bytes_read:location to store the number of bytes in the input string that were successfully converted, or None. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error GLib.ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
bytes_written:the number of bytes stored in the output buffer (not including the terminating nul).

Return type:

(str, bytes_read: int, bytes_written: int)

Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error GLib.ConvertError.ILLEGAL_SEQUENCE. If the source encoding is not UTF-8 and the conversion output contains a nul character, the error GLib.ConvertError.EMBEDDED_NUL is set and the function returns None. Use GLib.convert() to produce output that may contain embedded nul characters.

GLib.find_program_in_path(program)[source]
Parameters:program (str) – a program name in the GLib file name encoding
Returns:a newly-allocated string with the absolute path, or None
Return type:str

Locates the first executable named program in the user’s path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, or None if the program is not found in the path. If program is already an absolute path, returns a copy of program if program exists and is executable, and None otherwise.

On Windows, if program does not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in the PATHEXT environment variable.

On Windows, it looks for the file in the same way as CreateProcess() would. This means first in the directory where the executing program was loaded from, then in the current directory, then in the Windows 32-bit system directory, then in the Windows directory, and finally in the directories in the PATH environment variable. If the program is found, the return value contains the full name including the type suffix.

GLib.format_size(size)[source]
Parameters:size (int) – a size in bytes
Returns:a newly-allocated formatted string containing a human readable file size
Return type: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 prefix units base is 1000 (i.e. 1 kB is 1000 bytes).

This string should be freed with GLib.free() when not needed any longer.

See GLib.format_size_full() for more options about how the size might be formatted.

New in version 2.30.

GLib.format_size_for_display(size)[source]
Parameters:size (int) – a size in bytes
Returns:a newly-allocated formatted string containing a human readable file size
Return type: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 GLib.free() when not needed any longer.

New 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 GLib.format_size() instead.

GLib.format_size_full(size, flags)[source]
Parameters:
Returns:

a newly-allocated formatted string containing a human readable file size

Return type:

str

Formats a size.

This function is similar to GLib.format_size() but allows for flags that modify the output. See GLib.FormatSizeFlags.

New in version 2.30.

GLib.free(mem)[source]
Parameters:mem (object or None) – the memory to free

Frees the memory pointed to by mem.

If mem is None it simply returns, so there is no need to check mem against None before calling this function.

GLib.get_application_name()[source]
Returns:human-readable application name. may return None
Return type:str

Gets a human-readable name for the application, as set by GLib.set_application_name(). This name should be localized if possible, and is intended for display to the user. Contrast with GLib.get_prgname(), which gets a non-localized name. If GLib.set_application_name() has not been called, returns the result of GLib.get_prgname() (which may be None if GLib.set_prgname() has also not been called).

New in version 2.2.

GLib.get_charset()[source]
Returns:True if the returned charset is UTF-8
charset:return location for character set name, or None.
Return type:(bool, charset: str)

Obtains the character set for the current locale; you might use this character set as an argument to GLib.convert(), to convert from the current locale’s encoding to some other encoding. (Frequently GLib.locale_to_utf8() and GLib.locale_from_utf8() are nice shortcuts, though.)

On Windows the character set returned by this function is the so-called system default ANSI code-page. That is the character set used by the “narrow” versions of C library and Win32 functions that handle file names. It might be different from the character set used by the C library’s current locale.

On Linux, the character set is found by consulting nl_langinfo() if available. If not, the environment variables LC_ALL, LC_CTYPE, LANG and CHARSET are queried in order.

The return value is True if the locale’s encoding is UTF-8, in that case you can perhaps avoid calling GLib.convert().

The string returned in charset is not allocated, and should not be freed.

GLib.get_codeset()[source]
Returns:a newly allocated string containing the name of the character set. This string must be freed with GLib.free().
Return type:str

Gets the character set for the current locale.

GLib.get_current_dir()[source]
Returns:the current directory
Return type: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.

GLib.get_current_time()[source]
Returns:Time in seconds since the Epoch
Return type:float

Equivalent to the UNIX gettimeofday() function, but portable.

You may find GLib.get_real_time() to be more convenient.

GLib.get_environ()[source]
Returns:the list of environment variables
Return type:[str]

Gets the list of environment variables for the current process.

The list is None terminated and each item in the list is of the form ‘NAME=VALUE’.

This is equivalent to direct access to the ‘environ’ global variable, except portable.

The return value is freshly allocated and it should be freed with GLib.strfreev() when it is no longer needed.

New in version 2.28.

GLib.get_filename_charsets()[source]
Returns:True if the filename encoding is UTF-8.
filename_charsets:
 return location for the None-terminated list of encoding names
Return type:(bool, filename_charsets: [str])

Determines the preferred character sets used for filenames. The first character set from the charsets is the filename encoding, the subsequent character sets are used when trying to generate a displayable representation of a filename, see GLib.filename_display_name().

On Unix, the character sets are determined by consulting the environment variables G_FILENAME_ENCODING and G_BROKEN_FILENAMES. On Windows, the character set used in the GLib API is always UTF-8 and said environment variables have no effect.

G_FILENAME_ENCODING may be set to a comma-separated list of character set names. The special token “`locale`” is taken to mean the character set for the current locale. If G_FILENAME_ENCODING is not set, but G_BROKEN_FILENAMES is, the character set of the current locale is taken as the filename encoding. If neither environment variable is set, UTF-8 is taken as the filename encoding, but the character set of the current locale is also put in the list of encodings.

The returned charsets belong to GLib and must not be freed.

Note that on Unix, regardless of the locale character set or G_FILENAME_ENCODING value, the actual file names present on a system might be in any random encoding or just gibberish.

New in version 2.6.

GLib.get_home_dir()[source]
Returns:the current user’s home directory
Return type:str

Gets the current user’s home directory.

As with most UNIX tools, this function will return the value of the HOME environment variable if it is set to an existing absolute path name, falling back to the passwd file in the case that it is unset.

If the path given in HOME is non-absolute, does not exist, or is not a directory, the result is undefined.

Before version 2.36 this function would ignore the HOME environment variable, taking the value from the passwd database instead. This was changed to increase the compatibility of GLib with other programs (and the XDG basedir specification) and to increase testability of programs based on GLib (by making it easier to run them from test frameworks).

If your program has a strong requirement for either the new or the old behaviour (and if you don’t wish to increase your GLib dependency to ensure that the new behaviour is in effect) then you should either directly check the HOME environment variable yourself or unset it before calling any functions in GLib.

GLib.get_host_name()[source]
Returns:the host name of the machine.
Return type: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.

New in version 2.8.

GLib.get_language_names()[source]
Returns:a None-terminated array of strings owned by GLib that must not be modified or freed.
Return type:[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_MESSAGES and LANG to find the list of locales specified by the user.

New in version 2.6.

GLib.get_language_names_with_category(category_name)[source]
Parameters:category_name (str) – a locale category name
Returns:a None-terminated array of strings owned by GLib that must not be modified or freed.
Return type:[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, and LANG to find the list of locales specified by the user.

GLib.get_language_names() returns GLib.get_language_names_with_category(“LC_MESSAGES”).

New in version 2.58.

GLib.get_locale_variants(locale)[source]
Parameters:locale (str) – a locale identifier
Returns:a newly allocated array of newly allocated strings with the locale variants. Free with GLib.strfreev().
Return type:[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.

For example, if locale is “fr_BE”, then the returned list is “fr_BE”, “fr”.

If you need the list of variants for the current locale, use GLib.get_language_names().

New in version 2.28.

GLib.get_monotonic_time()[source]
Returns:the monotonic time, in microseconds
Return type: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.

New in version 2.28.

GLib.get_num_processors()[source]
Returns:Number of schedulable threads, always greater than 0
Return type: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 g_thread_pool_new() for CPU bound tasks and similar cases.

New in version 2.36.

GLib.get_prgname()[source]
Returns:the name of the program. The returned string belongs to GLib and must not be modified or freed.
Return type:str

Gets the name of the program. This name should not be localized, in contrast to GLib.get_application_name().

If you are using #GApplication the 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 the #GtkApplication::startup handler. The program name is found by taking the last component of argv[0].

GLib.get_real_name()[source]
Returns:the user’s real name.
Return type:str

Gets the real name of the user. This usually comes from the user’s entry in the passwd file. The encoding of the returned string is system-defined. (On Windows, it is, however, always UTF-8.) If the real user name cannot be determined, the string “Unknown” is returned.

GLib.get_real_time()[source]
Returns:the number of microseconds since January 1, 1970 UTC.
Return type:int

Queries the system wall-clock time.

This call is functionally equivalent to GLib.get_current_time() except that the return value is often more convenient than dealing with a GLib.TimeVal.

You should only use this call if you are actually interested in the real wall-clock time. GLib.get_monotonic_time() is probably more useful for measuring intervals.

New in version 2.28.

GLib.get_system_config_dirs()[source]
Returns:a None-terminated array of strings owned by GLib that must not be modified or freed.
Return type:[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_DIRS is defined. If XDG_CONFIG_DIRS is undefined, the directory that contains application data for all users is used instead. A typical path is C:\Documents and Settings\All Users\Application Data. This folder is used for application data that is not user specific. For example, an application can store a spell-check dictionary, a database of clip art, or a log file in the CSIDL_COMMON_APPDATA folder. This information will not roam and is available to anyone using the computer.

New in version 2.6.

GLib.get_system_data_dirs()[source]
Returns:a None-terminated array of strings owned by GLib that must not be modified or freed.
Return type:[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_DIRS is defined. If XDG_DATA_DIRS is undefined, the first elements in the list are the Application Data and Documents folders for All Users. (These can be determined only on Windows 2000 or later and are not present in the list on other Windows versions.) See documentation for CSIDL_COMMON_APPDATA and CSIDL_COMMON_DOCUMENTS.

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.

New in version 2.6.

GLib.get_tmp_dir()[source]
Returns:the directory to use for temporary files.
Return type:str

Gets the directory to use for temporary files.

On UNIX, this is taken from the TMPDIR environment variable. If the variable is not set, P_tmpdir is used, as defined by the system C library. Failing that, a hard-coded default of “/tmp” is returned.

On Windows, the TEMP environment variable is used, with the root directory of the Windows installation (eg: “C:") used as a default.

The encoding of the returned string is system-defined. On Windows, it is always UTF-8. The return value is never None or the empty string.

GLib.get_user_cache_dir()[source]
Returns:a string owned by GLib that must not be modified or freed.
Return type: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_HOME is defined. If XDG_CACHE_HOME is undefined, the directory that serves as a common repository for temporary Internet files is used instead. A typical path is C:\Documents and Settings\username\Local Settings\Temporary Internet Files. See the documentation for CSIDL_INTERNET_CACHE.

New in version 2.6.

GLib.get_user_config_dir()[source]
Returns:a string owned by GLib that must not be modified or freed.
Return type: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_HOME is defined. If XDG_CONFIG_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for CSIDL_LOCAL_APPDATA. Note that in this case on Windows it will be the same as what GLib.get_user_data_dir() returns.

New in version 2.6.

GLib.get_user_data_dir()[source]
Returns:a string owned by GLib that must not be modified or freed.
Return type: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_HOME is defined. If XDG_DATA_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for CSIDL_LOCAL_APPDATA. Note that in this case on Windows it will be the same as what GLib.get_user_config_dir() returns.

New in version 2.6.

GLib.get_user_name()[source]
Returns:the user name of the current user.
Return type: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.

GLib.get_user_runtime_dir()[source]
Returns:a string owned by GLib that must not be modified or freed.
Return type: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_DIR environment variable. In the case that this variable is not set, we return the value of GLib.get_user_cache_dir(), after verifying that it exists.

New in version 2.28.

GLib.get_user_special_dir(directory)[source]
Parameters:directory (GLib.UserDirectory) – the logical id of special directory
Returns:the path to the specified special directory, or None if the logical id was not found. The returned string is owned by GLib and should not be modified or freed.
Return type:str

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, GLib.UserDirectory.DIRECTORY_DESKTOP falls back to $HOME/Desktop when XDG special user directories have not been set up.

Depending on the platform, the user might be able to change the path of the special directory without requiring the session to restart; GLib will not reflect any change once the special directories are loaded.

New in version 2.14.

GLib.getenv(variable)[source]
Parameters:variable (str) – the environment variable to get
Returns:the value of the environment variable, or None if the environment variable is not found. The returned string may be overwritten by the next call to GLib.getenv(), GLib.setenv() or GLib.unsetenv().
Return type:str

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.

GLib.hash_table_add(hash_table, key)[source]
Parameters:
Returns:

True if the key did not exist yet

Return type:

bool

This is a convenience function for using a GLib.HashTable as a set. It is equivalent to calling GLib.HashTable.replace() with key as both the key and the value.

When a hash table only ever contains keys that have themselves as the corresponding value it is able to be stored more efficiently. See the discussion in the section description.

Starting from GLib 2.40, this function returns a boolean value to indicate whether the newly added value was already in the hash table or not.

New in version 2.32.

GLib.hash_table_contains(hash_table, key)[source]
Parameters:
Returns:

True if key is in hash_table, False otherwise.

Return type:

bool

Checks if key is in hash_table.

New in version 2.32.

GLib.hash_table_destroy(hash_table)[source]
Parameters:hash_table ({object: object}) – a GLib.HashTable

Destroys all keys and values in the GLib.HashTable and decrements its reference count by 1. If keys and/or values are dynamically allocated, you should either free them first or create the GLib.HashTable with destroy notifiers using g_hash_table_new_full(). In the latter case the destroy functions you supplied will be called on all keys and values during the destruction phase.

GLib.hash_table_insert(hash_table, key, value)[source]
Parameters:
Returns:

True if the key did not exist yet

Return type:

bool

Inserts a new key and value into a GLib.HashTable.

If the key already exists in the GLib.HashTable its current value is replaced with the new value. If you supplied a value_destroy_func when creating the GLib.HashTable, the old value is freed using that function. If you supplied a key_destroy_func when creating the GLib.HashTable, the passed key is freed using that function.

Starting from GLib 2.40, this function returns a boolean value to indicate whether the newly added value was already in the hash table or not.

GLib.hash_table_lookup(hash_table, key)[source]
Parameters:
Returns:

the associated value, or None if the key is not found

Return type:

object or None

Looks up a key in a GLib.HashTable. Note that this function cannot distinguish between a key that is not present and one which is present and has the value None. If you need this distinction, use GLib.HashTable.lookup_extended().

GLib.hash_table_lookup_extended(hash_table, lookup_key)[source]
Parameters:
Returns:

True if the key was found in the GLib.HashTable

orig_key:return location for the original key
value:return location for the value associated with the key

Return type:

(bool, orig_key: object, value: object)

Looks up a key in the GLib.HashTable, returning the original key and the associated value and a bool which is True if the key was found. This is useful if you need to free the memory allocated for the original key, for example before calling GLib.HashTable.remove().

You can actually pass None for lookup_key to test whether the None key exists, provided the hash and equal functions of hash_table are None-safe.

GLib.hash_table_remove(hash_table, key)[source]
Parameters:
Returns:

True if the key was found and removed from the GLib.HashTable

Return type:

bool

Removes a key and its associated value from a GLib.HashTable.

If the GLib.HashTable was created using g_hash_table_new_full(), the key and value are freed using the supplied destroy functions, otherwise you have to make sure that any dynamically allocated values are freed yourself.

GLib.hash_table_remove_all(hash_table)[source]
Parameters:hash_table ({object: object}) – a GLib.HashTable

Removes all keys and their associated values from a GLib.HashTable.

If the GLib.HashTable was created using g_hash_table_new_full(), the keys and values are freed using the supplied destroy functions, otherwise you have to make sure that any dynamically allocated values are freed yourself.

New in version 2.12.

GLib.hash_table_replace(hash_table, key, value)[source]
Parameters:
Returns:

True if the key did not exist yet

Return type:

bool

Inserts a new key and value into a GLib.HashTable similar to GLib.HashTable.insert(). The difference is that if the key already exists in the GLib.HashTable, it gets replaced by the new key. If you supplied a value_destroy_func when creating the GLib.HashTable, the old value is freed using that function. If you supplied a key_destroy_func when creating the GLib.HashTable, the old key is freed using that function.

Starting from GLib 2.40, this function returns a boolean value to indicate whether the newly added value was already in the hash table or not.

GLib.hash_table_size(hash_table)[source]
Parameters:hash_table ({object: object}) – a GLib.HashTable
Returns:the number of key/value pairs in the GLib.HashTable.
Return type:int

Returns the number of elements contained in the GLib.HashTable.

GLib.hash_table_steal(hash_table, key)[source]
Parameters:
Returns:

True if the key was found and removed from the GLib.HashTable

Return type:

bool

Removes a key and its associated value from a GLib.HashTable without calling the key and value destroy functions.

GLib.hash_table_steal_all(hash_table)[source]
Parameters:hash_table ({object: object}) – a GLib.HashTable

Removes all keys and their associated values from a GLib.HashTable without calling the key and value destroy functions.

New in version 2.12.

GLib.hash_table_steal_extended(hash_table, lookup_key)[source]
Parameters:
Returns:

True if the key was found in the GLib.HashTable

stolen_key:return location for the original key
stolen_value:return location for the value associated with the key

Return type:

(bool, stolen_key: object, stolen_value: object)

Looks up a key in the GLib.HashTable, stealing the original key and the associated value and returning True if the key was found. If the key was not found, False is returned.

If found, the stolen key and value are removed from the hash table without calling the key and value destroy functions, and ownership is transferred to the caller of this method; as with GLib.HashTable.steal().

You can pass None for lookup_key, provided the hash and equal functions of hash_table are None-safe.

New in version 2.58.

GLib.hash_table_unref(hash_table)[source]
Parameters:hash_table ({object: object}) – a valid GLib.HashTable

Atomically decrements the reference count of hash_table by one. If the reference count drops to 0, all keys and values will be destroyed, and all memory allocated by the hash table is released. This function is MT-safe and may be called from any thread.

New in version 2.10.

GLib.hook_destroy(hook_list, hook_id)[source]
Parameters:
Returns:

True if the GLib.Hook was found in the GLib.HookList and destroyed

Return type:

bool

Destroys a GLib.Hook, given its ID.

Parameters:

Removes one GLib.Hook from a GLib.HookList, marking it inactive and calling GLib.Hook.unref() on it.

GLib.hook_free(hook_list, hook)[source]
Parameters:

Calls the GLib.HookList finalize_hook function if it exists, and frees the memory allocated for the GLib.Hook.

GLib.hook_insert_before(hook_list, sibling, hook)[source]
Parameters:

Inserts a GLib.Hook into a GLib.HookList, before a given GLib.Hook.

GLib.hook_prepend(hook_list, hook)[source]
Parameters:

Prepends a GLib.Hook on the start of a GLib.HookList.

GLib.hook_unref(hook_list, hook)[source]
Parameters:

Decrements the reference count of a GLib.Hook. If the reference count falls to 0, the GLib.Hook is removed from the GLib.HookList and GLib.Hook.free() is called to free it.

GLib.hostname_is_ascii_encoded(hostname)[source]
Parameters:hostname (str) – a hostname
Returns:True if hostname contains any ASCII-encoded segments.
Return type:bool

Tests if hostname contains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returns True, you should decode the hostname with GLib.hostname_to_unicode() before displaying it to the user.

Note that a hostname might contain a mix of encoded and unencoded segments, and so it is possible for GLib.hostname_is_non_ascii() and GLib.hostname_is_ascii_encoded() to both return True for a name.

New in version 2.22.

GLib.hostname_is_ip_address(hostname)[source]
Parameters:hostname (str) – a hostname (or IP address in string form)
Returns:True if hostname is an IP address
Return type:bool

Tests if hostname is the string form of an IPv4 or IPv6 address. (Eg, “192.168.0.1”.)

New in version 2.22.

GLib.hostname_is_non_ascii(hostname)[source]
Parameters:hostname (str) – a hostname
Returns:True if hostname contains any non-ASCII characters
Return type:bool

Tests if hostname contains Unicode characters. If this returns True, you need to encode the hostname with GLib.hostname_to_ascii() before using it in non-IDN-aware contexts.

Note that a hostname might contain a mix of encoded and unencoded segments, and so it is possible for GLib.hostname_is_non_ascii() and GLib.hostname_is_ascii_encoded() to both return True for a name.

New in version 2.22.

GLib.hostname_to_ascii(hostname)[source]
Parameters:hostname (str) – a valid UTF-8 or ASCII hostname
Returns:an ASCII hostname, which must be freed, or None if hostname is in some way invalid.
Return type:str

Converts hostname to its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot.

New in version 2.22.

GLib.hostname_to_unicode(hostname)[source]
Parameters:hostname (str) – a valid UTF-8 or ASCII hostname
Returns:a UTF-8 hostname, which must be freed, or None if hostname is in some way invalid.
Return type:str

Converts hostname to its canonical presentation form; a UTF-8 string in Unicode normalization form C, containing no uppercase letters, no forbidden characters, and no ASCII-encoded segments, and not ending with a trailing dot.

Of course if hostname is not an internationalized hostname, then the canonical presentation form will be entirely ASCII.

New in version 2.22.

GLib.idle_add(priority, function, *data)[source]
Parameters:
Returns:

the ID (greater than 0) of the event source.

Return type:

int

Adds a function to be called whenever there are no higher priority events pending. If the function returns False it is automatically removed from the list of event sources and will not be called again.

See memory management of sources for details on how to handle the return value and memory management of data.

This internally creates a main loop source using GLib.idle_source_new() and attaches it to the global GLib.MainContext using GLib.Source.attach(), so the callback will be invoked in whichever thread is running that main context. You can do these steps manually if you need greater control or to use a custom main context.

GLib.idle_remove_by_data(data)[source]
Parameters:data (object or None) – the data for the idle source’s callback.
Returns:True if an idle source was found and removed.
Return type:bool

Removes the idle function with the given data.

GLib.idle_source_new()[source]
Returns:the newly-created idle source
Return type:GLib.Source

Creates a new idle source.

The source will not initially be associated with any GLib.MainContext and must be added to one with GLib.Source.attach() before it will be executed. Note that the default priority for idle sources is GLib.PRIORITY_DEFAULT_IDLE, as compared to other sources which have a default priority of GLib.PRIORITY_DEFAULT.

GLib.int64_equal(v1, v2)[source]
Parameters:
  • v1 (object) – a pointer to a #gint64 key
  • v2 (object) – a pointer to a #gint64 key to compare with v1
Returns:

True if the two keys match.

Return type:

bool

Compares the two #gint64 values being pointed to and returns True if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-None pointers to 64-bit integers as keys in a GLib.HashTable.

New in version 2.22.

GLib.int64_hash(v)[source]
Parameters:v (object) – a pointer to a #gint64 key
Returns:a hash value corresponding to the key.
Return type:int

Converts a pointer to a #gint64 to a hash value.

It can be passed to g_hash_table_new() as the hash_func parameter, when using non-None pointers to 64-bit integer values as keys in a GLib.HashTable.

New in version 2.22.

GLib.int_equal(v1, v2)[source]
Parameters:
  • v1 (object) – a pointer to a int key
  • v2 (object) – a pointer to a int key to compare with v1
Returns:

True if the two keys match.

Return type:

bool

Compares the two int values being pointed to and returns True if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-None pointers to integers as keys in a GLib.HashTable.

Note that this function acts on pointers to int, not on int directly: if your hash table’s keys are of the form GINT_TO_POINTER (n), use GLib.direct_equal() instead.

GLib.int_hash(v)[source]
Parameters:v (object) – a pointer to a int key
Returns:a hash value corresponding to the key.
Return type:int

Converts a pointer to a int to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using non-None pointers to integer values as keys in a GLib.HashTable.

Note that this function acts on pointers to int, not on int directly: if your hash table’s keys are of the form GINT_TO_POINTER (n), use GLib.direct_hash() instead.

GLib.intern_static_string(string)[source]
Parameters:string (str or None) – a static string
Returns:a canonical representation for the string
Return type:str

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp(). GLib.intern_static_string() does not copy the string, therefore string must not be freed or modified.

New in version 2.10.

GLib.intern_string(string)[source]
Parameters:string (str or None) – a string
Returns:a canonical representation for the string
Return type:str

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp().

New in version 2.10.

GLib.io_add_watch(channel, priority, condition, func, *user_data)[source]
Parameters:
  • channel – a GLib.IOChannel
  • priority – the priority of the GLib.IOChannel source
  • condition – the condition to watch for
  • func – the function to call when the condition is satisfied
  • user_data – user data to pass to func
Returns:

the event source id

Return type:

event_source_id

Adds the GLib.IOChannel into the default main loop context with the given priority.

This internally creates a main loop source using GLib.io_create_watch() and attaches it to the main loop context with GLib.Source.attach(). You can do these steps manually if you need greater control.

GLib.io_channel_error_from_errno(en)[source]
Parameters:en (int) – an errno error number, e.g. EINVAL
Returns:a GLib.IOChannelError error number, e.g. GLib.IOChannelError.INVAL.
Return type:GLib.IOChannelError

Converts an errno error number to a GLib.IOChannelError.

GLib.io_channel_error_quark()[source]
Return type:int
GLib.io_create_watch(channel, condition)[source]
Parameters:
Returns:

a new GLib.Source

Return type:

GLib.Source

Creates a GLib.Source that’s dispatched when condition is met for the given channel. For example, if condition is GLib.IOCondition.IN, the source will be dispatched when there’s data available for reading.

GLib.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 GLib.Source created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

GLib.key_file_error_quark()[source]
Return type:int
GLib.listenv()[source]
Returns:a None-terminated list of strings which must be freed with GLib.strfreev().
Return type:[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 GLib.getenv() instead of using the environ array from the C library directly. On Windows, the strings in the environ array are in system codepage encoding, while in most of the typical use cases for environment variables in GLib-using programs you want the UTF-8 encoding that this function and GLib.getenv() provide.

New in version 2.8.

GLib.locale_from_utf8(utf8string, len)[source]
Parameters:
  • utf8string (str) – a UTF-8 encoded string
  • len (int) – the length of the string, or -1 if the string is nul-terminated.
Raises:

GLib.Error

Returns:

A newly-allocated buffer containing the converted string, or None on an error, and error will be set.

bytes_read:location to store the number of bytes in the input string that were successfully converted, or None. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error GLib.ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.

Return type:

(bytes, bytes_read: 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. On Windows this means the system codepage.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error GLib.ConvertError.ILLEGAL_SEQUENCE. Use GLib.convert() to convert input that may contain embedded nul characters.

GLib.locale_to_utf8(opsysstring)[source]
Parameters:opsysstring (bytes) – a string in the encoding of the current locale. On Windows this means the system codepage.
Raises:GLib.Error
Returns:The converted string, or None on an error.
bytes_read:location to store the number of bytes in the input string that were successfully converted, or None. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error GLib.ConvertError.ILLEGAL_SEQUENCE occurs, the value stored will be the byte offset after the last valid input sequence.
bytes_written:the number of bytes stored in the output buffer (not including the terminating nul).
Return type:(str, bytes_read: int, bytes_written: 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 into a UTF-8 string.

If the source encoding is not UTF-8 and the conversion output contains a nul character, the error GLib.ConvertError.EMBEDDED_NUL is set and the function returns None. If the source encoding is UTF-8, an embedded nul character is treated with the GLib.ConvertError.ILLEGAL_SEQUENCE error for backward compatibility with earlier versions of this library. Use GLib.convert() to produce output that may contain embedded nul characters.

GLib.log_default_handler(log_domain, log_level, message, unused_data)[source]
Parameters:
  • log_domain (str or None) – the log domain of the message, or None for the default “” application domain
  • log_level (GLib.LogLevelFlags) – the level of the message
  • message (str or None) – the message
  • unused_data (object or None) – data passed from g_log() which is unused

The default log handler set up by GLib; g_log_set_default_handler() allows to install an alternate default log handler. This is used if no log handler has been set for the particular log domain and log level combination. It outputs the message to stderr or stdout and if the log level is fatal it calls G_BREAKPOINT(). It automatically prints a new-line character after the message, so one does not need to be manually included in message.

The behavior of this log handler can be influenced by a number of environment variables:

  • G_MESSAGES_PREFIXED: A :-separated list of log levels for which messages should be prefixed by the program name and PID of the aplication.
  • G_MESSAGES_DEBUG: A space-separated list of log domains for which debug and informational messages are printed. By default these messages are not printed.

stderr is used for levels GLib.LogLevelFlags.LEVEL_ERROR, GLib.LogLevelFlags.LEVEL_CRITICAL, GLib.LogLevelFlags.LEVEL_WARNING and GLib.LogLevelFlags.LEVEL_MESSAGE. stdout is used for the rest.

This has no effect if structured logging is enabled; see Using Structured Logging.

GLib.log_remove_handler(log_domain, handler_id)[source]
Parameters:

Removes the log handler.

This has no effect if structured logging is enabled; see Using Structured Logging.

GLib.log_set_always_fatal(fatal_mask)[source]
Parameters:fatal_mask (GLib.LogLevelFlags) – the mask containing bits set for each level of error which is to be fatal
Returns:the old fatal mask
Return type:GLib.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. GLib.LogLevelFlags.LEVEL_ERROR is always fatal.

You can also make some message levels fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

Libraries should not call this function, as it affects all messages logged by a process, including those from other libraries.

Structured log messages (using g_log_structured() and GLib.log_structured_array()) are fatal only if the default log writer is used; otherwise it is up to the writer function to determine which log messages are fatal. See Using Structured Logging.

GLib.log_set_fatal_mask(log_domain, fatal_mask)[source]
Parameters:
Returns:

the old fatal mask for the log domain

Return type:

GLib.LogLevelFlags

Sets the log levels which are fatal in the given domain. GLib.LogLevelFlags.LEVEL_ERROR is always fatal.

This has no effect on structured log messages (using g_log_structured() or GLib.log_structured_array()). To change the fatal behaviour for specific log messages, programs must install a custom log writer function using GLib.log_set_writer_func(). See Using Structured Logging.

This function is mostly intended to be used with GLib.LogLevelFlags.LEVEL_CRITICAL. You should typically not set GLib.LogLevelFlags.LEVEL_WARNING, GLib.LogLevelFlags.LEVEL_MESSAGE, GLib.LogLevelFlags.LEVEL_INFO or GLib.LogLevelFlags.LEVEL_DEBUG as fatal except inside of test programs.

GLib.log_set_handler(log_domain, log_levels, log_func, *user_data)[source]
Parameters:
Returns:

the id of the new handler

Return type:

int

Like GLib.log_set_handler(), but takes a destroy notify for the user_data.

This has no effect if structured logging is enabled; see Using Structured Logging.

New in version 2.46.

GLib.log_set_writer_func(*user_data)[source]
Parameters:user_data (object or None) – user data to pass to func

Set a writer function which will be called to format and write out each log message. Each program should set a writer function, or the default writer (GLib.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.

New in version 2.50.

GLib.log_structured_array(log_level, fields)[source]
Parameters:

Log a message with structured data. The message will be passed through to the log writer set by the application using GLib.log_set_writer_func(). If the message is fatal (i.e. its log level is GLib.LogLevelFlags.LEVEL_ERROR), the program will be aborted at the end of this function.

See g_log_structured() for more documentation.

This assumes that log_level is already present in fields (typically as the PRIORITY field).

New in version 2.50.

GLib.log_variant(log_domain, log_level, fields)[source]
Parameters:

Log a message with structured data, accepting the data within a GLib.Variant. This version is especially useful for use in other languages, via introspection.

The only mandatory item in the fields dictionary is the “MESSAGE” which must contain the text shown to the user.

The values in the fields dictionary are likely to be of type String (#G_VARIANT_TYPE_STRING). Array of bytes (#G_VARIANT_TYPE_BYTESTRING) is also supported. In this case the message is handled as binary and will be forwarded to the log writer as such. The size of the array should not be higher than %G_MAXSSIZE. Otherwise it will be truncated to this size. For other types GLib.Variant.print_() will be used to convert the value into a string.

For more details on its usage and about the parameters, see g_log_structured().

New in version 2.50.

GLib.log_writer_default(log_level, fields, user_data)[source]
Parameters:
Returns:

GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise

Return type:

GLib.LogWriterOutput

Format a structured log message and output it to the default log destination for the platform. On Linux, this is typically the systemd journal, falling back to stdout or stderr if running from the terminal or if output is being redirected to a file.

Support for other platform-specific logging mechanisms may be added in future. Distributors of GLib may modify this function to impose their own (documented) platform-specific log writing policies.

This is suitable for use as a GLib.LogWriterFunc, and is the default writer used if no other is set using GLib.log_set_writer_func().

As with GLib.log_default_handler(), this function drops debug and informational messages unless their log domain (or all) is listed in the space-separated G_MESSAGES_DEBUG environment variable.

New in version 2.50.

GLib.log_writer_format_fields(log_level, fields, use_color)[source]
Parameters:
Returns:

string containing the formatted log message, in the character set of the current locale

Return type:

str

Format a structured log message as a string suitable for outputting to the terminal (or elsewhere). This will include the values of all fields it knows how to interpret, which includes MESSAGE and GLIB_DOMAIN (see the documentation for g_log_structured()). It does not include values from unknown fields.

The returned string does **not** have a trailing new-line character. It is encoded in the character set of the current locale, which is not necessarily UTF-8.

New in version 2.50.

GLib.log_writer_is_journald(output_fd)[source]
Parameters:output_fd (int) – output file descriptor to check
Returns:True if output_fd points to the journal, False otherwise
Return type:bool

Check whether the given output_fd file descriptor is a connection to the systemd journal, or something else (like a log file or stdout or stderr).

Invalid file descriptors are accepted and return False, which allows for the following construct without needing any additional error handling:

is_journald = g_log_writer_is_journald (fileno (stderr));

New in version 2.50.

GLib.log_writer_journald(log_level, fields, user_data)[source]
Parameters:
Returns:

GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise

Return type:

GLib.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 GLib.LogWriterFunc.

If GLib has been compiled without systemd support, this function is still defined, but will always return GLib.LogWriterOutput.UNHANDLED.

New in version 2.50.

GLib.log_writer_standard_streams(log_level, fields, user_data)[source]
Parameters:
Returns:

GLib.LogWriterOutput.HANDLED on success, GLib.LogWriterOutput.UNHANDLED otherwise

Return type:

GLib.LogWriterOutput

Format a structured log message and print it to either stdout or stderr, depending on its log level. GLib.LogLevelFlags.LEVEL_INFO and GLib.LogLevelFlags.LEVEL_DEBUG messages are sent to stdout; all other log levels are sent to stderr. Only fields which are understood by this function are included in the formatted string which is printed.

If the output stream supports ANSI color escape sequences, they will be used in the output.

A trailing new-line character is added to the log message when it is printed.

This is suitable for use as a GLib.LogWriterFunc.

New in version 2.50.

GLib.log_writer_supports_color(output_fd)[source]
Parameters:output_fd (int) – output file descriptor to check
Returns:True if ANSI color escapes are supported, False otherwise
Return type:bool

Check whether the given output_fd file descriptor supports ANSI color escape sequences. If so, they can safely be used when formatting log messages.

New in version 2.50.

GLib.main_context_default()[source]
Returns:the global default main context.
Return type:GLib.MainContext

Returns the global default main context. This is the main context used for main loop functions when a main loop is not explicitly specified, and corresponds to the “main” main loop. See also GLib.MainContext.get_thread_default().

GLib.main_context_get_thread_default()[source]
Returns:the thread-default GLib.MainContext, or None if the thread-default context is the global default context.
Return type:GLib.MainContext

Gets the thread-default GLib.MainContext for this thread. Asynchronous operations that want to be able to be run in contexts other than the default one should call this method or GLib.MainContext.ref_thread_default() to get a GLib.MainContext to add their GLib.Sources to. (Note that even in single-threaded programs applications may sometimes want to temporarily push a non-default context, so it is not safe to assume that this will always return None if you are running in the default thread.)

If you need to hold a reference on the context, use GLib.MainContext.ref_thread_default() instead.

New in version 2.22.

GLib.main_context_ref_thread_default()[source]
Returns:the thread-default GLib.MainContext. Unref with GLib.MainContext.unref() when you are done with it.
Return type:GLib.MainContext

Gets the thread-default GLib.MainContext for this thread, as with GLib.MainContext.get_thread_default(), but also adds a reference to it with GLib.MainContext.ref(). In addition, unlike GLib.MainContext.get_thread_default(), if the thread-default context is the global default context, this will return that GLib.MainContext (with a ref added to it) rather than returning None.

New in version 2.32.

GLib.main_current_source()[source]
Returns:The currently firing source or None.
Return type:GLib.Source

Returns the currently firing source for this thread.

New in version 2.12.

GLib.main_depth()[source]
Returns:The main loop recursion level in the current thread
Return type:int

Returns the depth of the stack of calls to GLib.MainContext.dispatch() on any GLib.MainContext in the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback from GLib.MainContext.iteration() (or GLib.MainLoop.run(), etc.) it returns 1. When called from within a callback to a recursive call to GLib.MainContext.iteration(), it returns 2. And so forth.

This function is useful in a situation like the following: Imagine an extremely simple “garbage collected” system.

static GList *free_list;

gpointer
allocate_memory (gsize size)
{
  gpointer result = g_malloc (size);
  free_list = g_list_prepend (free_list, result);
  return result;
}

void
free_allocated_memory (void)
{
  GList *l;
  for (l = free_list; l; l = l->next);
    g_free (l->data);
  g_list_free (free_list);
  free_list = NULL;
 }

[...]

while (TRUE);
 {
   g_main_context_iteration (NULL, TRUE);
   free_allocated_memory();
  }

This works from an application, however, if you want to do the same thing from a library, it gets more difficult, since you no longer control the main loop. You might think you can simply use an idle function to make the call to free_allocated_memory(), but that doesn’t work, since the idle function could be called from a recursive callback. This can be fixed by using GLib.main_depth()

gpointer
allocate_memory (gsize size)
{
  FreeListBlock *block = g_new (FreeListBlock, 1);
  block->mem = g_malloc (size);
  block->depth = g_main_depth ();
  free_list = g_list_prepend (free_list, block);
  return block->mem;
}

void
free_allocated_memory (void)
{
  GList *l;

  int depth = g_main_depth ();
  for (l = free_list; l; );
    {
      GList *next = l->next;
      FreeListBlock *block = l->data;
      if (block->depth > depth)
        {
          g_free (block->mem);
          g_free (block);
          free_list = g_list_delete_link (free_list, l);
        }

      l = next;
    }
  }

There is a temptation to use GLib.main_depth() to solve problems with reentrancy. For instance, while waiting for data to be received from the network in response to a menu item, the menu item might be selected again. It might seem that one could make the menu item’s callback return immediately and do nothing if GLib.main_depth() returns a value greater than 1. However, this should be avoided since the user then sees selecting the menu item do nothing. Furthermore, you’ll find yourself adding these checks all over your code, since there are doubtless many, many things that the user could do. Instead, you can use the following techniques:

Use gtk_widget_set_sensitive() or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.

Avoid main loop recursion in situations where you can’t handle arbitrary callbacks. Instead, structure your code so that you simply return to the main loop and then get called again when there is more work to do.

GLib.malloc(n_bytes)[source]
Parameters:n_bytes (int) – the number of bytes to allocate
Returns:a pointer to the allocated memory
Return type:object or None

Allocates n_bytes bytes of memory. If n_bytes is 0 it returns None.

GLib.malloc0(n_bytes)[source]
Parameters:n_bytes (int) – the number of bytes to allocate
Returns:a pointer to the allocated memory
Return type:object or None

Allocates n_bytes bytes of memory, initialized to 0’s. If n_bytes is 0 it returns None.

GLib.malloc0_n(n_blocks, n_block_bytes)[source]
Parameters:
  • n_blocks (int) – the number of blocks to allocate
  • n_block_bytes (int) – the size of each block in bytes
Returns:

a pointer to the allocated memory

Return type:

object or None

This function is similar to GLib.malloc0(), allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

New in version 2.24.

GLib.malloc_n(n_blocks, n_block_bytes)[source]
Parameters:
  • n_blocks (int) – the number of blocks to allocate
  • n_block_bytes (int) – the size of each block in bytes
Returns:

a pointer to the allocated memory

Return type:

object or None

This function is similar to GLib.malloc(), allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

New in version 2.24.

GLib.markup_error_quark()[source]
Return type:int
GLib.markup_escape_text(text, length)[source]
Parameters:
  • text (str) – some valid UTF-8 text
  • length (int) – length of text in bytes, or -1 if the text is nul-terminated
Returns:

a newly allocated string with the escaped text

Return type:

str

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 &#x1; … &#x1f; 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.

GLib.mem_is_system_malloc()[source]
Returns:if True, malloc() and GLib.malloc() can be mixed.
Return type:bool

Checks whether the allocator used by GLib.malloc() is the system’s malloc implementation. If it returns True memory allocated with malloc() can be used interchangeable with memory allocated using GLib.malloc(). 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.

GLib.mem_profile()[source]

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

GLib.mem_set_vtable(vtable)[source]
Parameters:vtable (GLib.MemVTable) – table of memory allocation routines.

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

GLib.memdup(mem, byte_size)[source]
Parameters:
  • mem (object or None) – the memory to copy.
  • byte_size (int) – the number of bytes to copy.
Returns:

a pointer to the newly-allocated copy of the memory, or None if mem is None.

Return type:

object or None

Allocates byte_size bytes of memory, and copies byte_size bytes into it from mem. If mem is None it returns None.

GLib.mkdir_with_parents(pathname, mode)[source]
Parameters:
  • pathname (str) – a pathname in the GLib file name encoding
  • mode (int) – 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.

Return type:

int

Create a directory if it doesn’t already exist. Create intermediate parent directories as needed, too.

New in version 2.8.

GLib.nullify_pointer(nullify_location)[source]
Parameters:nullify_location (object) – the memory address of the pointer.

Set the pointer at the specified location to None.

GLib.number_parser_error_quark()[source]
Return type:int
GLib.on_error_query(prg_name)[source]
Parameters:prg_name (str) – the program name, needed by gdb for the “[S]tack trace” option. If prg_name is None, GLib.get_prgname() is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called)

Prompts the user with [E]xit, [H]alt, show [S]tack trace or [P]roceed. This function is intended to be used for debugging use only. The following example shows how it can be used together with the g_log() functions.

#include <glib.h>

static void
log_handler (const gchar   *log_domain,
             GLogLevelFlags log_level,
             const gchar   *message,
             gpointer       user_data)
{
  g_log_default_handler (log_domain, log_level, message, user_data);

  g_on_error_query (MY_PROGRAM_NAME);
}

int
main (int argc, char *argv[])
{
  g_log_set_handler (MY_LOG_DOMAIN,
                     G_LOG_LEVEL_WARNING |
                     G_LOG_LEVEL_ERROR |
                     G_LOG_LEVEL_CRITICAL,
                     log_handler,
                     NULL);
  ...

If “[E]xit” is selected, the application terminates with a call to _exit(0).

If “[S]tack” trace is selected, GLib.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.

GLib.on_error_stack_trace(prg_name)[source]
Parameters:prg_name (str) – the program name, needed by gdb for the “[S]tack trace” option

Invokes gdb, which attaches to the current process and shows a stack trace. Called by GLib.on_error_query() when the “[S]tack trace” option is selected. You can get the current process’s program name with GLib.get_prgname(), assuming that you have called gtk_init() or gdk_init().

This function may cause different actions on non-UNIX platforms.

GLib.once_init_enter(location)[source]
Parameters:location (object) – location of a static initializable variable containing 0
Returns:True if the initialization section should be entered, False and blocks otherwise
Return type:bool

Function to be called when starting a critical initialization section. The argument location must point to a static 0-initialized variable that will be set to a value other than 0 at the end of the initialization section. In combination with GLib.Once.init_leave() and the unique address value_location, it can be ensured that an initialization section will be executed only once during a program’s life time, and that concurrent threads are blocked until initialization completed. To be used in constructs like this:

static gsize initialization_value = 0;

if (g_once_init_enter (&initialization_value))
  {
    gsize setup_value = 42; // initialization code here

    g_once_init_leave (&initialization_value, setup_value);
  }

// use initialization_value here

New in version 2.14.

GLib.once_init_leave(location, result)[source]
Parameters:
  • location (object) – location of a static initializable variable containing 0
  • result (int) – new non-0 value for value_location

Counterpart to GLib.Once.init_enter(). Expects a location of a static 0-initialized initialization variable, and an initialization value other than 0. Sets the variable to the initialization value, and releases concurrent threads blocking in GLib.Once.init_enter() on this initialization variable.

New in version 2.14.

GLib.option_error_quark()[source]
Return type:int
GLib.parse_debug_string(string, keys)[source]
Parameters:
  • string (str or None) – a list of debug options separated by colons, spaces, or commas, or None.
  • keys ([GLib.DebugKey]) – pointer to an array of GLib.DebugKey which associate strings with bit flags.
Returns:

the combined set of bit flags.

Return type:

int

Parses a string containing debugging options into a int containing bit flags. This is used within GDK and GTK+ to parse the debug options passed on the command line or through environment variables.

If string is equal to “all”, all flags are set. Any flags specified along with “all” in string are inverted; thus, “all,foo,bar” or “foo,bar,all” sets all flags except those corresponding to “foo” and “bar”.

If string is equal to “help”, all the available keys in keys are printed out to standard error.

GLib.path_get_basename(file_name)[source]
Parameters:file_name (str) – the name of the file
Returns:a newly allocated string containing the last component of the filename
Return type:str

Gets the last component of the filename.

If file_name ends with a directory separator it gets the component before the last slash. If file_name consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. If file_name is empty, it gets “.”.

GLib.path_get_dirname(file_name)[source]
Parameters:file_name (str) – the name of the file
Returns:the directory components of the file
Return type:str

Gets the directory components of a file name.

If the file name has no directory components “.” is returned. The returned string should be freed when no longer needed.

GLib.path_is_absolute(file_name)[source]
Parameters:file_name (str) – a file name
Returns:True if file_name is absolute
Return type:bool

Returns True if the given file_name is an absolute file name. Note that this is a somewhat vague concept on Windows.

On POSIX systems, an absolute file name is well-defined. It always starts from the single root directory. For example “/usr/local”.

On Windows, the concepts of current drive and drive-specific current directory introduce vagueness. This function interprets as an absolute file name one that either begins with a directory separator such as “\Users\tml” or begins with the root on a drive, for example “C:\Windows”. The first case also includes UNC paths such as “\\myserver\docs\foo”. In all cases, either slashes or backslashes are accepted.

Note that a file name relative to the current drive root does not truly specify a file uniquely over time and across processes, as the current drive is a per-process value and can be changed.

File names relative the current directory on some specific drive, such as “D:foo/bar”, are not interpreted as absolute by this function, but they obviously are not relative to the normal current directory as returned by getcwd() or GLib.get_current_dir() either. Such paths should be avoided, or need to be handled using Windows-specific code.

GLib.path_skip_root(file_name)[source]
Parameters:file_name (str) – a file name
Returns:a pointer into file_name after the root component
Return type:str or None

Returns a pointer into file_name after the root component, i.e. after the “/” in UNIX or “C:" under Windows. If file_name is not an absolute path it returns None.

GLib.pattern_match(pspec, string_length, string, string_reversed)[source]
Parameters:
Returns:

True if string matches pspec

Return type:

bool

Matches a string against a compiled pattern. Passing the correct length of the string given is mandatory. The reversed string can be omitted by passing None, this is more efficient if the reversed version of the string to be matched is not at hand, as GLib.pattern_match() will only construct it if the compiled pattern requires reverse matches.

Note that, if the user code will (possibly) match a string against a multitude of patterns containing wildcards, chances are high that some patterns will require a reversed string. In this case, it’s more efficient to provide the reversed string to avoid multiple constructions thereof in the various calls to GLib.pattern_match().

Note also that the reverse of a UTF-8 encoded string can in general not be obtained by GLib.strreverse(). This works only if the string does not contain any multibyte characters. GLib offers the GLib.utf8_strreverse() function to reverse UTF-8 encoded strings.

GLib.pattern_match_simple(pattern, string)[source]
Parameters:
  • pattern (str) – the UTF-8 encoded pattern
  • string (str) – the UTF-8 encoded string to match
Returns:

True if string matches pspec

Return type:

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 g_pattern_spec_new() and call GLib.pattern_match_string() repeatedly.

GLib.pattern_match_string(pspec, string)[source]
Parameters:
Returns:

True if string matches pspec

Return type:

bool

Matches a string against a compiled pattern. If the string is to be matched against more than one pattern, consider using GLib.pattern_match() instead while supplying the reversed string.

GLib.pointer_bit_lock(address, lock_bit)[source]
Parameters:
  • address (object) – a pointer to a object-sized value
  • lock_bit (int) – a bit value between 0 and 31

This is equivalent to GLib.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.

New in version 2.30.

GLib.pointer_bit_trylock(address, lock_bit)[source]
Parameters:
  • address (object) – a pointer to a object-sized value
  • lock_bit (int) – a bit value between 0 and 31
Returns:

True if the lock was acquired

Return type:

bool

This is equivalent to GLib.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.

New in version 2.30.

GLib.pointer_bit_unlock(address, lock_bit)[source]
Parameters:
  • address (object) – a pointer to a object-sized value
  • lock_bit (int) – a bit value between 0 and 31

This is equivalent to GLib.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.

New in version 2.30.

GLib.poll(fds, nfds, timeout)[source]
Parameters:
  • fds (GLib.PollFD) – file descriptors to poll
  • nfds (int) – the number of file descriptors in fds
  • timeout (int) – amount of time to wait, in milliseconds, or -1 to wait forever
Returns:

the number of entries in fds whose revents fields were filled in, or 0 if the operation timed out, or -1 on error or if the call was interrupted.

Return type:

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 by GLib.MainContext, but it can be called directly if you need to block until a file descriptor is ready, but don’t want to run the full main loop.

Each element of fds is a GLib.PollFD describing a single file descriptor to poll. The fd field indicates the file descriptor, and the events field indicates the events to poll for. On return, the revents fields will be filled with the events that actually occurred.

On POSIX systems, the file descriptors in fds can be any sort of file descriptor, but the situation is much more complicated on Windows. If you need to use GLib.poll() in code that has to run on Windows, the easiest solution is to construct all of your GLib.PollFDs with g_io_channel_win32_make_pollfd().

New in version 2.20.

GLib.propagate_error(src)[source]
Parameters:src (GLib.Error) – error to move into the return location
Returns:error return location
Return type:dest: GLib.Error or None

If dest is None, free src; otherwise, moves src into dest. The error variable dest points to must be None.

src must be non-None.

Note that src is no longer valid after this call. If you want to keep using the same GLib.Error, you need to set it to None after calling this function on it.

GLib.quark_from_static_string(string)[source]
Parameters:string (str or None) – a string
Returns:the #GQuark identifying the string, or 0 if string is None
Return type:int

Gets the #GQuark identifying the given (static) string. If the string does not currently have an associated #GQuark, a new #GQuark is created, linked to the given string.

Note that this function is identical to GLib.quark_from_string() except that if a new #GQuark is created the string itself is used rather than a copy. This saves memory, but can only be used if the string will continue to exist until the program terminates. It can be used with statically allocated strings in the main program, but not with statically allocated memory in dynamically loaded modules, if you expect to ever unload the module again (e.g. do not use this function in GTK+ theme engines).

GLib.quark_from_string(string)[source]
Parameters:string (str or None) – a string
Returns:the #GQuark identifying the string, or 0 if string is None
Return type:int

Gets the #GQuark identifying the given string. If the string does not currently have an associated #GQuark, a new #GQuark is created, using a copy of the string.

GLib.quark_to_string(quark)[source]
Parameters:quark (int) – a #GQuark.
Returns:the string associated with the #GQuark
Return type:str

Gets the string associated with the given #GQuark.

GLib.quark_try_string(string)[source]
Parameters:string (str or None) – a string
Returns:the #GQuark associated with the string, or 0 if string is None or there is no #GQuark associated with it
Return type:int

Gets the #GQuark associated with the given string, or 0 if string is None or it has no associated #GQuark.

If you want the GQuark to be created if it doesn’t already exist, use GLib.quark_from_string() or GLib.quark_from_static_string().

GLib.random_double()[source]
Returns:a random number
Return type:float

Returns a random float equally distributed over the range [0..1).

GLib.random_double_range(begin, end)[source]
Parameters:
  • begin (float) – lower closed bound of the interval
  • end (float) – upper open bound of the interval
Returns:

a random number

Return type:

float

Returns a random float equally distributed over the range [begin..`end`).

GLib.random_int()[source]
Returns:a random number
Return type:int

Return a random #guint32 equally distributed over the range [0..2^32-1].

GLib.random_int_range(begin, end)[source]
Parameters:
  • begin (int) – lower closed bound of the interval
  • end (int) – upper open bound of the interval
Returns:

a random number

Return type:

int

Returns a random #gint32 equally distributed over the range [begin..`end`-1].

GLib.random_set_seed(seed)[source]
Parameters:seed (int) – a value to reinitialize the global random number generator

Sets the seed for the global random number generator, which is used by the g_random_* functions, to seed.

GLib.rc_box_acquire(mem_block)[source]
Parameters:mem_block (object) – a pointer to reference counted data
Returns:a pointer to the data, with its reference count increased
Return type:object

Acquires a reference on the data pointed by mem_block.

New in version 2.58.

GLib.rc_box_alloc(block_size)[source]
Parameters:block_size (int) – the size of the allocation, must be greater than 0
Returns:a pointer to the allocated memory
Return type:object

Allocates block_size bytes of memory, and adds reference counting semantics to it.

The data will be freed when its reference count drops to zero.

New in version 2.58.

GLib.rc_box_alloc0(block_size)[source]
Parameters:block_size (int) – the size of the allocation, must be greater than 0
Returns:a pointer to the allocated memory
Return type:object

Allocates block_size bytes of memory, and adds reference counting semantics to it.

The contents of the returned data is set to zero.

The data will be freed when its reference count drops to zero.

New in version 2.58.

GLib.rc_box_dup(block_size, mem_block)[source]
Parameters:
  • block_size (int) – the number of bytes to copy, must be greater than 0
  • mem_block (object) – the memory to copy
Returns:

a pointer to the allocated memory

Return type:

object

Allocates a new block of data with reference counting semantics, and copies block_size bytes of mem_block into it.

New in version 2.58.

GLib.rc_box_get_size(mem_block)[source]
Parameters:mem_block (object) – a pointer to reference counted data
Returns:the size of the data, in bytes
Return type:int

Retrieves the size of the reference counted data pointed by mem_block.

New in version 2.58.

GLib.rc_box_release(mem_block)[source]
Parameters:mem_block (object) – a pointer to reference counted data

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.

New in version 2.58.

GLib.rc_box_release_full(mem_block, clear_func)[source]
Parameters:
  • mem_block (object) – a pointer to reference counted data
  • clear_func (GLib.DestroyNotify) – a function to call when clearing the data

Releases a reference on the data pointed by mem_block.

If the reference was the last one, it will call clear_func to clear the contents of mem_block, and then will free the resources allocated for mem_block.

New in version 2.58.

GLib.realloc(mem, n_bytes)[source]
Parameters:
  • mem (object or None) – the memory to reallocate
  • n_bytes (int) – new size of the memory in bytes
Returns:

the new address of the allocated memory

Return type:

object or None

Reallocates the memory pointed to by mem, so that it now has space for n_bytes bytes of memory. It returns the new address of the memory, which may have been moved. mem may be None, in which case it’s considered to have zero-length. n_bytes may be 0, in which case None will be returned and mem will be freed unless it is None.

GLib.realloc_n(mem, n_blocks, n_block_bytes)[source]
Parameters:
  • mem (object or None) – the memory to reallocate
  • n_blocks (int) – the number of blocks to allocate
  • n_block_bytes (int) – the size of each block in bytes
Returns:

the new address of the allocated memory

Return type:

object or None

This function is similar to GLib.realloc(), allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

New in version 2.24.

GLib.ref_string_acquire(str)[source]
Parameters:str (str) – a reference counted string
Returns:the given string, with its reference count increased
Return type:str

Acquires a reference on a string.

New in version 2.58.

GLib.ref_string_length(str)[source]
Parameters:str (str) – a reference counted string
Returns:the length of the given string, in bytes
Return type:int

Retrieves the length of str.

New in version 2.58.

GLib.ref_string_new(str)[source]
Parameters:str (str) – a NUL-terminated string
Returns:the newly created reference counted string
Return type:str

Creates a new reference counted string and copies the contents of str into it.

New in version 2.58.

GLib.ref_string_new_intern(str)[source]
Parameters:str (str) – a NUL-terminated string
Returns:the newly created reference counted string, or a new reference to an existing string
Return type:str

Creates a new reference counted string and copies the content of str into it.

If you call this function multiple times with the same str, or with the same contents of str, it will return a new reference, instead of creating a new string.

New in version 2.58.

GLib.ref_string_new_len(str, len)[source]
Parameters:
  • str (str) – a string
  • len (int) – length of str to use, or -1 if str is nul-terminated
Returns:

the newly created reference counted string

Return type:

str

Creates a new reference counted string and copies the contents of str into it, up to len bytes.

Since this function does not stop at nul bytes, it is the caller’s responsibility to ensure that str has at least len addressable bytes.

New in version 2.58.

GLib.ref_string_release(str)[source]
Parameters:str (str) – a reference counted string

Releases a reference on a string; if it was the last reference, the resources allocated by the string are freed as well.

New in version 2.58.

GLib.regex_check_replacement(replacement)[source]
Parameters:replacement (str) – the replacement string
Raises:GLib.Error
Returns:whether replacement is a valid replacement string
has_references:location to store information about references in replacement or None
Return type:(bool, has_references: bool)

Checks whether replacement is a valid replacement string (see GLib.Regex.replace()), i.e. that all escape sequences in it are valid.

If has_references is not None then replacement is checked for pattern references. For instance, replacement text ‘foo\n’ does not contain references and may be evaluated without information about actual match, but ‘\0\1’ (whole match followed by first subpattern) requires valid GLib.MatchInfo object.

New in version 2.14.

GLib.regex_error_quark()[source]
Return type:int
GLib.regex_escape_nul(string, length)[source]
Parameters:
  • string (str) – the string to escape
  • length (int) – the length of string
Returns:

a newly-allocated escaped string

Return type:

str

Escapes the nul characters in string to “\x00”. It can be used to compile a regex with embedded nul characters.

For completeness, length can be -1 for a nul-terminated string. In this case the output string will be of course equal to string.

New in version 2.30.

GLib.regex_escape_string(string)[source]
Parameters:string ([str]) – the string to escape
Returns:a newly-allocated escaped string
Return type:str

Escapes the special characters used for regular expressions in string, for instance “a.b*c” becomes “a.b\*c”. This function is useful to dynamically generate regular expressions.

string can contain nul characters that are replaced with “\0”, in this case remember to specify the correct length of string in length.

New in version 2.14.

GLib.regex_match_simple(pattern, string, compile_options, match_options)[source]
Parameters:
  • pattern (str) – the regular expression
  • string (str) – the string to scan for matches
  • compile_options (GLib.RegexCompileFlags) – compile options for the regular expression, or 0
  • match_options (GLib.RegexMatchFlags) – match options, or 0
Returns:

True if the string matched, False otherwise

Return type:

bool

Scans for a match in string for pattern.

This function is equivalent to GLib.Regex.match() but it does not require to compile the pattern with GLib.Regex.new(), avoiding some lines of code when you need just to do a match without extracting substrings, capture counts, and so on.

If this function is to be called on the same pattern more than once, it’s more efficient to compile the pattern once with GLib.Regex.new() and then use GLib.Regex.match().

New in version 2.14.

GLib.regex_split_simple(pattern, string, compile_options, match_options)[source]
Parameters:
  • pattern (str) – the regular expression
  • string (str) – the string to scan for matches
  • compile_options (GLib.RegexCompileFlags) – compile options for the regular expression, or 0
  • match_options (GLib.RegexMatchFlags) – match options, or 0
Returns:

a None-terminated array of strings. Free it using GLib.strfreev()

Return type:

[str]

Breaks the string on the pattern, and returns an array of the tokens. If the pattern contains capturing parentheses, then the text for each of the substrings will also be returned. If the pattern does not match anywhere in the string, then the whole string is returned as the first token.

This function is equivalent to GLib.Regex.split() but it does not require to compile the pattern with GLib.Regex.new(), avoiding some lines of code when you need just to do a split without extracting substrings, capture counts, and so on.

If this function is to be called on the same pattern more than once, it’s more efficient to compile the pattern once with GLib.Regex.new() and then use GLib.Regex.split().

As a special case, the result of splitting the empty string “” is an empty vector, not a vector containing a single string. The reason for this special case is that being able to represent a empty vector 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 this function.

A pattern that can match empty strings splits string into separate characters wherever it matches the empty string between characters. For example splitting “ab c” using as a separator “\s*”, you will get “a”, “b” and “c”.

New in version 2.14.

GLib.reload_user_special_dirs_cache()[source]

Resets the cache used for GLib.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 threadsafety issues this may cause leaking of strings that were previously returned from GLib.get_user_special_dir() that can’t be freed. We ensure to only leak the data for the directories that actually changed value though.

New in version 2.22.

GLib.rmdir(filename)[source]
Parameters:filename (str) – 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
Return type: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.

New in version 2.6.

GLib.sequence_get(iter)[source]
Parameters:iter (GLib.SequenceIter) – a GLib.SequenceIter
Returns:the data that iter points to
Return type:object or None

Returns the data that iter points to.

New in version 2.14.

GLib.sequence_insert_before(iter, data)[source]
Parameters:
Returns:

an iterator pointing to the new item

Return type:

GLib.SequenceIter

Inserts a new item just before the item pointed to by iter.

New in version 2.14.

GLib.sequence_move(src, dest)[source]
Parameters:

Moves the item pointed to by src to the position indicated by dest. After calling this function dest will point to the position immediately after src. It is allowed for src and dest to point into different sequences.

New in version 2.14.

GLib.sequence_move_range(dest, begin, end)[source]
Parameters:

Inserts the (begin, end) range at the destination pointed to by dest. The begin and end iters must point into the same sequence. It is allowed for dest to point to a different sequence than the one pointed into by begin and end.

If dest is None, the range indicated by begin and end is removed from the sequence. If dest points to a place within the (begin, end) range, the range does not move.

New in version 2.14.

GLib.sequence_range_get_midpoint(begin, end)[source]
Parameters:
Returns:

a GLib.SequenceIter pointing somewhere in the (begin, end) range

Return type:

GLib.SequenceIter

Finds an iterator somewhere in the range (begin, end). This iterator will be close to the middle of the range, but is not guaranteed to be exactly in the middle.

The begin and end iterators must both point to the same sequence and begin must come before or be equal to end in the sequence.

New in version 2.14.

GLib.sequence_remove(iter)[source]
Parameters:iter (GLib.SequenceIter) – a GLib.SequenceIter

Removes the item pointed to by iter. It is an error to pass the end iterator to this function.

If the sequence has a data destroy function associated with it, this function is called on the data for the removed item.

New in version 2.14.

GLib.sequence_remove_range(begin, end)[source]
Parameters:

Removes all items in the (begin, end) range.

If the sequence has a data destroy function associated with it, this function is called on the data for the removed items.

New in version 2.14.

GLib.sequence_set(iter, data)[source]
Parameters:

Changes the data for the item pointed to by iter to be data. If the sequence has a data destroy function associated with it, that function is called on the existing data that iter pointed to.

New in version 2.14.

GLib.sequence_swap(a, b)[source]
Parameters:

Swaps the items pointed to by a and b. It is allowed for a and b to point into difference sequences.

New in version 2.14.

GLib.set_application_name(application_name)[source]
Parameters:application_name (str) – localized name of the application

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 GLib.set_prgname(), which sets a non-localized name. GLib.set_prgname() will be called automatically by gtk_init(), but GLib.set_application_name() will not.

Note that for thread safety reasons, this function can only be called once.

The application name will be used in contexts such as error messages, or when displaying an application’s name in the task list.

New in version 2.2.

GLib.set_error_literal(domain, code, message)[source]
Parameters:
  • domain (int) – error domain
  • code (int) – error code
  • message (str) – error message
Returns:

a return location for a GLib.Error

Return type:

err: GLib.Error

Does nothing if err is None; if err is non-None, then err must be None. A new GLib.Error is created and assigned to err. Unlike g_set_error(), message is not a printf()-style format string. Use this function if message contains text you don’t have control over, that could include printf() escape sequences.

New in version 2.18.

GLib.set_prgname(prgname)[source]
Parameters:prgname (str) – the name of the program.

Sets the name of the program. This name should not be localized, in contrast to GLib.set_application_name().

If you are using #GApplication the 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 the #GtkApplication::startup handler. The program name is found by taking the last component of argv[0].

Note that for thread-safety reasons this function can only be called once.

GLib.setenv(variable, value, overwrite)[source]
Parameters:
  • variable (str) – the environment variable to set, must not contain ‘=’.
  • value (str) – the value for to set the variable to.
  • overwrite (bool) – whether to change the variable if it already exists.
Returns:

False if the environment variable couldn’t be set.

Return type:

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 GLib.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 GLib.get_environ() to get an environment array, modify that with GLib.environ_setenv() and GLib.environ_unsetenv(), and then pass that array directly to execvpe(), GLib.spawn_async(), or the like.

New in version 2.4.

GLib.shell_error_quark()[source]
Return type:int
GLib.shell_parse_argv(command_line)[source]
Parameters:command_line (str) – command line to parse
Raises:GLib.Error
Returns:True on success, False if error set
argvp:return location for array of args
Return type:(bool, argvp: [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. Free the returned vector with GLib.strfreev().

GLib.shell_quote(unquoted_string)[source]
Parameters:unquoted_string (str) – a literal string
Returns:quoted string
Return type: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 GLib.free(). The quoting style used is undefined (single or double quotes may be used).

GLib.shell_unquote(quoted_string)[source]
Parameters:quoted_string (str) – shell-quoted string
Raises:GLib.Error
Returns:an unquoted string
Return type:str

Unquotes a string as the shell (/bin/sh) would. 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 GLib.shell_quote(). If it fails, it returns None and sets the error. The quoted_string need not actually contain quoted or escaped text; GLib.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 GLib.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.

GLib.slice_alloc(block_size)[source]
Parameters:block_size (int) – the number of bytes to allocate
Returns:a pointer to the allocated memory block, which will be None if and only if mem_size is 0
Return type:object or None

Allocates a block of memory from the slice allocator. The block address handed out can be expected to be aligned to at least 1 * sizeof (void*), though in general slices are 2 * sizeof (void*) bytes aligned, if a malloc() fallback implementation is used instead, the alignment may be reduced in a libc dependent fashion. Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

New in version 2.10.

GLib.slice_alloc0(block_size)[source]
Parameters:block_size (int) – the number of bytes to allocate
Returns:a pointer to the allocated block, which will be None if and only if mem_size is 0
Return type:object or None

Allocates a block of memory via GLib.slice_alloc() and initializes the returned memory to 0. Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

New in version 2.10.

GLib.slice_copy(block_size, mem_block)[source]
Parameters:
  • block_size (int) – the number of bytes to allocate
  • mem_block (object or None) – the memory to copy
Returns:

a pointer to the allocated memory block, which will be None if and only if mem_size is 0

Return type:

object or None

Allocates a block of memory from the slice allocator and copies block_size bytes into it from mem_block.

mem_block must be non-None if block_size is non-zero.

New in version 2.14.

GLib.slice_free1(block_size, mem_block)[source]
Parameters:
  • block_size (int) – the size of the block
  • mem_block (object or None) – a pointer to the block to free

Frees a block of memory.

The memory must have been allocated via GLib.slice_alloc() or GLib.slice_alloc0() and the block_size has to match the size specified upon allocation. Note that the exact release behaviour can be changed with the ‘G_DEBUG=gc-friendly [G_DEBUG]’ environment variable, also see G_SLICE for related debugging options.

If mem_block is None, this function does nothing.

New in version 2.10.

GLib.slice_free_chain_with_offset(block_size, mem_chain, next_offset)[source]
Parameters:
  • block_size (int) – the size of the blocks
  • mem_chain (object or None) – a pointer to the first block of the chain
  • next_offset (int) – the offset of the next field in the blocks

Frees a linked list of memory blocks of structure type type.

The memory blocks must be equal-sized, allocated via GLib.slice_alloc() or GLib.slice_alloc0() and linked together by a next pointer (similar to GLib.SList). The offset of the next field in each block is passed as third argument. Note that the exact release behaviour can be changed with the ‘G_DEBUG=gc-friendly [G_DEBUG]’ environment variable, also see G_SLICE for related debugging options.

If mem_chain is None, this function does nothing.

New in version 2.10.

GLib.slice_get_config(ckey)[source]
Parameters:ckey (GLib.SliceConfig) –
Return type:int
GLib.slice_get_config_state(ckey, address, n_values)[source]
Parameters:
Return type:

int

GLib.slice_set_config(ckey, value)[source]
Parameters:
GLib.source_remove(tag)[source]
Parameters:tag (int) – the ID of the source to remove.
Returns:For historical reasons, this function always returns True
Return type:bool

Removes the source with the given ID from the default main context. You must use GLib.Source.destroy() for sources added to a non-default main context.

The ID of a GLib.Source is given by GLib.Source.get_id(), or will be returned by the functions GLib.Source.attach(), GLib.idle_add(), GLib.idle_add(), GLib.timeout_add(), GLib.timeout_add(), GLib.child_watch_add(), GLib.child_watch_add(), GLib.io_add_watch(), and GLib.io_add_watch().

It is a programmer error to attempt to remove a non-existent source.

More specifically: source IDs can be reissued after a source has been destroyed and therefore it is never valid to use this function with a source ID which may have already been removed. An example is when scheduling an idle to run in another thread with GLib.idle_add(): the idle may already have run and been removed by the time this function is called on its (now invalid) source ID. This source ID may have been reissued, leading to the operation being performed against the wrong source.

GLib.source_remove_by_funcs_user_data(funcs, user_data)[source]
Parameters:
Returns:

True if a source was found and removed.

Return type:

bool

Removes a source from the default main loop context given the source functions and user data. If multiple sources exist with the same source functions and user data, only one will be destroyed.

GLib.source_remove_by_user_data(user_data)[source]
Parameters:user_data (object or None) – the user_data for the callback.
Returns:True if a source was found and removed.
Return type:bool

Removes a source from the default main loop context given the user data for the callback. If multiple sources exist with the same user data, only one will be destroyed.

GLib.source_set_name_by_id(tag, name)[source]
Parameters:

Sets the name of a source using its ID.

This is a convenience utility to set source names from the return value of GLib.idle_add(), GLib.timeout_add(), etc.

It is a programmer error to attempt to set the name of a non-existent source.

More specifically: source IDs can be reissued after a source has been destroyed and therefore it is never valid to use this function with a source ID which may have already been removed. An example is when scheduling an idle to run in another thread with GLib.idle_add(): the idle may already have run and been removed by the time this function is called on its (now invalid) source ID. This source ID may have been reissued, leading to the operation being performed against the wrong source.

New in version 2.26.

GLib.spaced_primes_closest(num)[source]
Parameters:num (int) – a int
Returns:the smallest prime number from a built-in array of primes which is larger than num
Return type: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 a GLib.HashTable.

The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

GLib.spawn_async(argv, envp=None, working_directory=None, flags=GLib.SpawnFlags.DEFAULT, child_setup=None, user_data=None, standard_input=False, standard_output=False, standard_error=False)[source]
Parameters:
Raises:

GLib.Error

Returns:

pid:child process ID
stdin:file descriptor to child’s stdin, or None
stdout:file descriptor to read child’s stdout, or None
stderr:file descriptor to read child’s stderr, or None

Return type:

(pid: int, stdin: int or None, stdout: int or None, stderr: int or None)

See GLib.spawn_async_with_pipes() for a full description; this function simply calls the GLib.spawn_async_with_pipes()

You should call GLib.spawn_close_pid() on the returned child process reference when you don’t need it any more.

In case standard_input/standard_output/standard_error are True a file descriptor is returned which needs to be closed by the caller after it is no longer needed.

GLib.spawn_async_with_fds(working_directory, argv, envp, flags, child_setup, user_data, stdin_fd, stdout_fd, stderr_fd)[source]
Parameters:
  • working_directory (str or None) – child’s current working directory, or None to inherit parent’s, in the GLib file name encoding
  • argv ([str]) – child’s argument vector, in the GLib file name encoding
  • envp ([str] or None) – child’s environment, or None to inherit parent’s, in the GLib file name encoding
  • flags (GLib.SpawnFlags) – flags from GLib.SpawnFlags
  • child_setup (GLib.SpawnChildSetupFunc or None) – function to run in the child just before exec()
  • user_data (object or None) – user data for child_setup
  • stdin_fd (int) – file descriptor to use for child’s stdin, or -1
  • stdout_fd (int) – file descriptor to use for child’s stdout, or -1
  • stderr_fd (int) – file descriptor to use for child’s stderr, or -1
Raises:

GLib.Error

Returns:

True on success, False if an error was set

child_pid:return location for child process ID, or None

Return type:

(bool, child_pid: int)

Identical to GLib.spawn_async_with_pipes() but instead of creating pipes for the stdin/stdout/stderr, you can pass existing file descriptors into this function through the stdin_fd, stdout_fd and stderr_fd parameters. The following flags also have their behaviour slightly tweaked as a result:

GLib.SpawnFlags.STDOUT_TO_DEV_NULL means that the child’s standard output will be discarded, instead of going to the same location as the parent’s standard output. If you use this flag, standard_output must be -1. GLib.SpawnFlags.STDERR_TO_DEV_NULL means that the child’s standard error will be discarded, instead of going to the same location as the parent’s standard error. If you use this flag, standard_error must be -1. GLib.SpawnFlags.CHILD_INHERITS_STDIN means that the child will inherit the parent’s standard input (by default, the child’s standard input is attached to /dev/null). If you use this flag, standard_input must be -1.

It is valid to pass the same fd in multiple parameters (e.g. you can pass a single fd for both stdout and stderr).

New in version 2.58.

GLib.spawn_async_with_pipes(working_directory, argv, envp, flags, child_setup, *user_data)[source]
Parameters:
  • working_directory (str or None) – child’s current working directory, or None to inherit parent’s, in the GLib file name encoding
  • argv ([str]) – child’s argument vector, in the GLib file name encoding
  • envp ([str] or None) – child’s environment, or None to inherit parent’s, in the GLib file name encoding
  • flags (GLib.SpawnFlags) – flags from GLib.SpawnFlags
  • child_setup (GLib.SpawnChildSetupFunc or None) – function to run in the child just before exec()
  • user_data (object or None) – user data for child_setup
Raises:

GLib.Error

Returns:

True on success, False if an error was set

child_pid:return location for child process ID, or None
standard_input:return location for file descriptor to write to child’s stdin, or None
standard_output:
 return location for file descriptor to read child’s stdout, or None
standard_error:return location for file descriptor to read child’s stderr, or None

Return type:

(bool, child_pid: int, standard_input: int, standard_output: int, standard_error: int)

Executes a child program asynchronously (your program will not block waiting for the child to exit). The child program is specified by the only argument that must be provided, argv. argv should be a None-terminated array of strings, to be passed as the argument vector for the child. The first string in argv is of course the name of the program to execute. By default, the name of the program must b