from gi.repository import GObject def on_completion(source, res, user_data): exit_status, stdout, stderr = source.get_child_exit_status(source) print("Exit status: {}".format(exit_status)) print("Standard output: {}".format(stdout.read())) print("Standard error: {}".format(stderr.read())) GObject.spawn_async( None, # directory ['/bin/ls', '/usr'], None, # envp GObject.SpawnFlags.DO_NOT_REAP_CHILD, None, # child setup function None, # user data on_completion, None) # user data
from gi.repository import GObject, GLib def on_output(channel, condition, user_data): if condition == GLib.IOCondition.IN: data = bytes(channel.read_chars(1024)) print(data.decode('utf-8'), end='') GObject.spawn_async( None, # directory ['/bin/ping', '-c', '5', 'google.com'], None, # envp GObject.SpawnFlags.DO_NOT_REAP_CHILD, None, # child setup function None, # user data None, # exit callback None) # user data GLib.io_add_watch( 1, # stdout GLib.IOCondition.IN, on_output, None) # user dataThis example asynchronously spawns a new process to ping Google.com five times using the `ping` command. The standard output of the child process is continuously read using the `io_add_watch` function and printed to the console in real-time using the `on_output` function. Overall, the `spawn_async` method is commonly used for running external commands and retrieving their output and exit status in an asynchronous manner. It is a part of the GObject module within the gi.repository package library.