def execute(self, gfile): path = gfile.get_path() wd = gfile.get_parent().get_path() argv = self.makeArgv(path) cmdLine = " ".join(argv) print("Executing '%s'" %(cmdLine)) try: GLib.spawn_async(argv, working_directory = wd, \ flags = GLib.SPAWN_SEARCH_PATH) except GLib.Error as e: print("Failed to execute '%s': %s" %(cmdLine, e))
def _on_manage_passwords_clicked(self, button): """ Launch searhorse @param button as Gtk.Button """ argv = [GLib.find_program_in_path("seahorse")] GLib.spawn_async(argv)
def stop_systemd_timers(self): GLib.spawn_async([ '/usr/bin/systemctl', '--user', 'stop', 'theme-switcher-auto.timer' ]) GLib.spawn_async([ '/usr/bin/systemctl', '--user', 'disable', 'theme-switcher-auto.timer' ])
def run(self): app = read_desktop_file(self.filename) app_id = Path(self.filename).with_suffix('').stem exec = app.get_string('Exec') if not exec: logger.error("No command to run %s", self.filename) else: # strip field codes %f, %F, %u, %U, etc sanitized_exec = re.sub(r'\%[uUfFdDnNickvm]', '', exec).rstrip() terminal_exec = shlex.split( settings.get_property('terminal-command')) if app.get_boolean('Terminal'): if terminal_exec: logger.info('Will run command in preferred terminal (%s)', terminal_exec) sanitized_exec = terminal_exec + [sanitized_exec] else: sanitized_exec = ['gtk-launch', app_id] else: sanitized_exec = shlex.split(sanitized_exec) if runs_in_systemd and not app.get_boolean( 'X-Ulauncher-Inherit-Scope'): logger.warning( "Will attempt to launch the app using systemd-run with --scope argument" ) logger.warning( "This prevents the apps from terminating if Ulauncher crashes or is restarted." ) logger.warning( "On some systems with outdated systemd or incorrect permissions this doesn't work." ) logger.warning( "If this happens to you, don't run Ulauncher from systemd." ) sanitized_exec = [ 'systemd-run', '--user', '--scope', ] + sanitized_exec env = dict(os.environ.items()) # Make sure GDK apps aren't forced to use x11 on wayland due to ulauncher's need to run # under X11 for proper centering. env.pop("GDK_BACKEND", None) try: logger.info('Run application %s (%s) Exec %s', app.get_name(), self.filename, exec) envp = ["{}={}".format(k, v) for k, v in env.items()] GLib.spawn_async( argv=sanitized_exec, envp=envp, flags=GLib.SpawnFlags.SEARCH_PATH_FROM_ENVP | GLib.SpawnFlags.SEARCH_PATH, # setsid is really only needed if systemd-run is missing, but doesn't hurt to have. child_setup=os.setsid) except Exception as e: logger.error('%s: %s', type(e).__name__, e)
def ui_help(self, ui): '''The UI's help button was clicked. This should open a help HTML page or website, call yelp with an appropriate topic, etc. This gets the current UI object passed, which can be used to determine whether GTK/KDE is used, etc. ''' if 'gtk' in str(ui.__class__).lower(): GLib.spawn_async(['yelp', 'ghelp:jockey'], flags=GLib.SpawnFlags.SEARCH_PATH)
def activate(result, metadata, id): trace('activate') trace(metadata) note = result.uri parameters = [ NIXNOTE_EXECUTABLE, '--accountId=1', '--startMinimized', note ] trace(parameters) trace('spawning') GLib.spawn_async(parameters) return Unity.ActivationResponse(handled=Unity.HandledType.HIDE_DASH, goto_uri=None)
def spawn_async(argv, flags): if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) < (2, 30): _, pid = GLib.spawn_async( None, # Inherit current directory, argv, # Command with arguments. None, # Inherit environment. flags, None, # Child setup callback. None # User data. ) else: pid, _, _, _ = GLib.spawn_async(argv=argv, flags=flags) return pid
def _vmUpOperation(self): assert self.vmPid is None dbusObj = dbus.SystemBus().get_object('org.fpemud.VirtService', '/org/fpemud/VirtService') try: self.maxDriveId = 0 self.vmTmpDir = tempfile.mkdtemp(prefix="lightbox.vm.") self.vsVmResSetId = dbusObj.NewVmResSet( dbus_interface='org.fpemud.VirtService') resSetObj = dbus.SystemBus().get_object( 'org.fpemud.VirtService', '/org/fpemud/VirtService/%d/VmResSets/%d' % (os.getuid(), self.vsVmResSetId)) if self.vmCfg.networkAdapterInterface == "virtio": # resSetObj.AddTapIntf(self.vmEnv.getVirtioNetworkType()) resSetObj.AddTapIntf( "nat", dbus_interface='org.fpemud.VirtService.VmResSet') self.vsVmId = dbusObj.AttachVm( self.vmDir, self.vsVmResSetId, dbus_interface='org.fpemud.VirtService') self.vsTapIfName = resSetObj.GetTapIntf( dbus_interface='org.fpemud.VirtService.VmResSet') self.vsMacAddr = resSetObj.GetVmMacAddr( dbus_interface='org.fpemud.VirtService.VmResSet') self.vsIpAddr = resSetObj.GetVmIpAddr( dbus_interface='org.fpemud.VirtService.VmResSet') self.spicePort = FvpUtil.getFreeSocketPort( "tcp", self.param.spicePortStart, self.param.spicePortEnd) self.qmpPort = FvpUtil.getFreeSocketPort("tcp") qemuCmd = self._generateQemuCommand() mycwd = os.getcwd() os.chdir(self.vmDir) try: targc, targv = GLib.shell_parse_argv(qemuCmd) ret = GLib.spawn_async(targv, flags=GLib.SpawnFlags.DO_NOT_REAP_CHILD) self.vmPid = ret[0] self.vmPidWatch = GLib.child_watch_add(self.vmPid, self.onVmExit) time.sleep( 1) # fixme: should change fvp_vm_view, repeat connect finally: os.chdir(mycwd) self.qmpObj = qmp.QmpClient() self.qmpObj.connect_tcp("127.0.0.1", self.qmpPort) self.state = FvpVmObject.STATE_POWER_ON self.notify("state") except: self._vmDownOperation(True, dbusObj) raise
def start_child_process(self, args): # Start child process with C locale so we can parse the output env = os.environ.copy() env['LANG'] = env['LANGUAGE'] = env['LC_ALL'] = env['LC_MESSAGES'] = 'C' self.process = GLib.spawn_async(args, envp=['{}={}'.format(k,v) for k, v in env.items()], flags=GLib.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True)
def start_session(self, host, port, session, username, password, wait): """ Start a session using x2go """ # Start in the background and attach a watch for when it exits cmd = [ os.path.join(softwarecenter.paths.datadir, softwarecenter.paths.X2GO_HELPER) ] (self.helper_pid, stdin, stdout, stderr) = GLib.spawn_async(cmd, standard_input=True, standard_output=True, standard_error=True, flags=GObject.SPAWN_DO_NOT_REAP_CHILD) self.helper_stdin = os.fdopen(stdin, "w") self.helper_stdout = os.fdopen(stdout) self.helper_stderr = os.fdopen(stderr) # Add a watch for when the process exits GLib.child_watch_add(GLib.PRIORITY_DEFAULT, self.helper_pid, self._on_x2go_exit) # Add a watch on stdout channel = GLib.IOChannel.unix_new(self.helper_stdout) GLib.io_add_watch(channel, GLib.PRIORITY_DEFAULT, GObject.IO_IN, self._on_x2go_activity) # Start the connection self.state = "connecting" self.helper_stdin.write( "CONNECT: \"%s\" \"%s\" \"%s\" \"%s\" \"%s\"\n" % (host, port, username, password, session)) self.helper_stdin.flush()
def async_run_subprocess(command): pid, stdin, stdout, _ = \ GLib.spawn_async(command, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) return stdout
def copy_files(self, file_name, action): if action == 'make_backup': command = [ 'cp', '-R', self.winetricks_cache + '/' + file_name, self.winetricks_cache_backup ] elif action == 'restore_backup': command = [ 'cp', '-R', self.winetricks_cache_backup + '/' + file_name, self.winetricks_cache ] self.pid, stdin, stdout, stderr = GLib.spawn_async( command, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) io = GLib.IOChannel(stdout) self.source_id_out = io.add_watch(GLib.IO_IN | GLib.IO_HUP, self.watch_process, 'copy_files', priority=GLib.PRIORITY_HIGH)
def __set_popularity(self, pop): """ Set popularity as kid3 is installed @param pop as int """ try: if App().art.kid3_available: if pop == 0: value = 0 elif pop == 1: value = 1 elif pop == 2: value = 64 elif pop == 3: value = 128 elif pop == 4: value = 196 else: value = 255 path = GLib.filename_from_uri(self.__object.uri)[0] if GLib.find_program_in_path("flatpak-spawn") is not None: argv = ["flatpak-spawn", "--host", "kid3-cli", "-c", "set POPM %s" % value, path] else: argv = ["kid3-cli", "-c", "set POPM %s" % value, path] (pid, stdin, stdout, stderr) = GLib.spawn_async( argv, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.STDOUT_TO_DEV_NULL, standard_input=False, standard_output=False, standard_error=False ) except Exception as e: Logger.error("RatingWidget::__on_can_set_popularity(): %s" % e)
def _spawn_redshift_oneshot(self, args): # Start redshift with arguments args.insert(0, os.path.join(defs.BINDIR, 'redshift')) if '-r' not in args: args.append('-r') if '-P' not in args: args.append('-P') # Start child process with C locale so we can parse the output env = os.environ.copy() for key in ('LANG', 'LANGUAGE', 'LC_ALL', 'LC_MESSAGES'): env[key] = 'C' GLib.spawn_async( args, envp=['{}={}'.format(k, v) for k, v in env.items()], standard_output=True, standard_error=True)
def start(self): def readline(io, condition): if condition is GLib.IO_IN: line = io.readline() parts = line.strip().split() if len(parts) != 3: logger.debug( "Unexpected line from keypress viewer: {}".format( parts)) else: logger.debug("Got keypress details: '{}'".format(line)) self.emit("keypress", parts[0], parts[1], parts[2]) return True elif condition is GLib.IO_HUP | GLib.IO_IN: GLib.source_remove(self.source_id) return False keypress_viewer_exe = os.path.abspath( os.path.join(os.path.dirname(__file__), "listkeys-subprocess.py")) logger.info( "Starting KeypressViewer ({}).".format(keypress_viewer_exe)) argv = [sys.executable, keypress_viewer_exe] self.child_pid, stdin, stdout, stderr = GLib.spawn_async( argv, standard_output=True) io = GLib.IOChannel(stdout) self.source_id = io.add_watch(GLib.IO_IN | GLib.IO_HUP, readline, priority=GLib.PRIORITY_HIGH)
def __tag_editor_search(self, editors=TAG_EDITORS): """ Search for tag editor """ # Search for available tag editors if not self.__tag_editor and editors: editor = editors.pop(0) if GLib.find_program_in_path("flatpak-spawn") is not None: argv = [ "flatpak-spawn", "--host", "sh", "-c", 'command -v %s' % editor ] elif GLib.find_program_in_path(editor) is not None: self.__tag_editor = editor return try: (pid, stdin, stdout, stderr) = GLib.spawn_async( argv, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.STDOUT_TO_DEV_NULL | GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_input=False, standard_output=False, standard_error=False) GLib.child_watch_add(GLib.PRIORITY_DEFAULT_IDLE, pid, self.__on_tag_editor_result, editor, editors) except: self.__on_tag_editor_result(None, 1, editor, editors)
def spawn_child(argv, respawn=True, display=None): """ Spawn argv in the mainloop and keeping it as a child process (it will be made sure to exit with the parent). @respawn: If True, respawn if child dies abnormally raises utils.SpawnError returns pid """ flags = (GLib.SPAWN_SEARCH_PATH | GLib.SPAWN_DO_NOT_REAP_CHILD) envp = [] if display: # environment is passed as a sequence of strings envd = os.environ.copy() envd['DISPLAY'] = display envp[:] = ['='.join((k,v)) for k,v in list(envd.items())] try: pid, stdin_fd, stdout_fd, stderr_fd = \ GLib.spawn_async(argv, envp,flags=flags, child_setup=_try_register_pr_pdeathsig, ) except GLib.GError as exc: raise SpawnError(str(exc)) if pid: GLib.child_watch_add(pid, _on_child_exit, (argv, respawn)) return pid
def menu_activate_cb(self, menu, paths): '''Telling from amount of paths runs appropriate comparator engine''' if len(paths) == 1: self.for_later = paths[0] return cmd = None if len(paths) == 2: cmd = [self.config.diff_engine] + paths elif len(paths) == 3 and len(self.config.diff_engine_3way.strip()) > 0: cmd = [self.config.diff_engine_3way] + paths elif len(self.config.diff_engine_multi.strip()) > 0: cmd = [self.config.diff_engine_multi] + paths if cmd is not None: GLib.spawn_async(argv=cmd, flags=GLib.SpawnFlags.DEFAULT | GLib.SpawnFlags.SEARCH_PATH)
def run(self): """Run the process.""" # NOTE: DO_NOT_REAP_CHILD: the child will not be automatically reaped; # you must use g_child_watch_add yourself (or call waitpid or handle `SIGCHLD` yourself), # or the child will become a zombie. # source: # http://valadoc.org/#!api=glib-2.0/GLib.SpawnFlags.DO_NOT_REAP_CHILD # NOTE: SEARCH_PATH: argv[0] need not be an absolute path, it will be looked for in the user’s PATH # source: # http://lazka.github.io/pgi-docs/#GLib-2.0/flags.html#GLib.SpawnFlags.SEARCH_PATH self.pid, self.stdin, self.stdout, self.stderr = GLib.spawn_async(self.command, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD ) logger.debug("command: ".format(self.command)) logger.debug("stdin: ".format(self.stdin)) logger.debug("stdout: ".format(self.stdout)) logger.debug("stderr: ".format(self.stderr)) logger.debug("pid: ".format(self.pid)) # close file descriptor self.pid.close() print self.stderr # NOTE: GLib.PRIORITY_HIGH = -100 # Use this for high priority event sources. # It is not used within GLib or GTK+. watch = GLib.child_watch_add(GLib.PRIORITY_HIGH, self.pid, self.exited_cb) return self.pid
def __init__(self, args): '''Initialize controller and start child process The parameter args is a list of command line arguments to pass on to the child process. The "-v" argument is automatically added.''' GObject.GObject.__init__(self) # Initialize state variables self._inhibited = False self._temperature = 0 self._period = 'Unknown' self._location = (0.0, 0.0) # Start redshift with arguments args.insert(0, os.path.join(defs.BINDIR, 'redshift')) if '-v' not in args: args.insert(1, '-v') # Start child process with C locale so we can parse the output env = os.environ.copy() env['LANG'] = env['LANGUAGE'] = env['LC_ALL'] = env['LC_MESSAGES'] = 'C' self._process = GLib.spawn_async(args, envp=['{}={}'.format(k,v) for k, v in env.items()], flags=GLib.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) # Wrap remaining contructor in try..except to avoid that the child # process is not closed properly. try: # Handle child input # The buffer is encapsulated in a class so we # can pass an instance to the child callback. class InputBuffer(object): buf = '' self._input_buffer = InputBuffer() self._error_buffer = InputBuffer() self._errors = '' # Set non blocking fcntl.fcntl(self._process[2], fcntl.F_SETFL, fcntl.fcntl(self._process[2], fcntl.F_GETFL) | os.O_NONBLOCK) # Add watch on child process GLib.child_watch_add(GLib.PRIORITY_DEFAULT, self._process[0], self._child_cb) GLib.io_add_watch(self._process[2], GLib.PRIORITY_DEFAULT, GLib.IO_IN, self._child_data_cb, (True, self._input_buffer)) GLib.io_add_watch(self._process[3], GLib.PRIORITY_DEFAULT, GLib.IO_IN, self._child_data_cb, (False, self._error_buffer)) # Signal handler to relay USR1 signal to redshift process def relay_signal_handler(signal): os.kill(self._process[0], signal) return True GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGUSR1, relay_signal_handler, signal.SIGUSR1) except: self.termwait() raise
def __init__(self, argv, finish_callback, timeout_s, stdin=None, env=None): self.stdout = [] self.stderr = [] self.stdin = [] self.timeout = False self.killed = False self.finished = False self.finish_callback = finish_callback # FIXME: No byte string support self.output_debug("AsyncCommand:", argv) flags = (GLib.SPAWN_SEARCH_PATH | GLib.SPAWN_DO_NOT_REAP_CHILD) kwargs = {} if env is not None: kwargs['envp'] = env pid, stdin_fd, stdout_fd, stderr_fd = \ GLib.spawn_async(argv, standard_output=True, standard_input=True, standard_error=True, flags=flags, **kwargs) if stdin: self.stdin[:] = self._split_string(stdin, self.max_input_buf) in_io_flags = GLib.IO_OUT | GLib.IO_ERR | GLib.IO_HUP | GLib.IO_NVAL GLib.io_add_watch(stdin_fd, in_io_flags, self._in_io_callback, self.stdin) else: os.close(stdin_fd) io_flags = GLib.IO_IN | GLib.IO_ERR | GLib.IO_HUP | GLib.IO_NVAL GLib.io_add_watch(stdout_fd, io_flags, self._io_callback, self.stdout) GLib.io_add_watch(stderr_fd, io_flags, self._io_callback, self.stderr) self.pid = pid GLib.child_watch_add(pid, self._child_callback) if timeout_s is not None: GLib.timeout_add_seconds(timeout_s, self._timeout_callback)
def run(self, cmd): # only useful for debugging if "SOFTWARE_CENTER_DISABLE_SPAWN_HELPER" in os.environ: return self._cmd = cmd (pid, stdin, stdout, stderr) = GLib.spawn_async(cmd, flags=GObject.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) if (Globals.DEBUG_SWITCH): LOG.debug("running: '%s' as pid: '%s'" % (cmd, pid)) # python-gobject >= 3.7.3 has changed some API in incompatible # ways, so we need to check the version for which one to use. if gi_version < (3, 7, 3): self._child_watch = GLib.child_watch_add(pid, self._helper_finished, (stdout, stderr)) self._io_watch = GLib.io_add_watch(stdout, GObject.IO_IN, self._helper_io_ready, (stdout, )) else: self._child_watch = GLib.child_watch_add(GLib.PRIORITY_DEFAULT, pid, self._helper_finished, data=(stdout, stderr)) self._io_watch = GLib.io_add_watch(stdout, GLib.PRIORITY_DEFAULT, GObject.IO_IN, self._helper_io_ready, (stdout, ))
def _run_lintian(self, filename): buf = self.textview_lintian_output.get_buffer() if not os.path.exists("/usr/bin/lintian"): buf.set_text( _("No lintian available.\n" "Please install using sudo apt-get install lintian")) return buf.set_text(_("Running lintian...")) self._lintian_output = "" self._lintian_exit_status = None self._lintian_exit_status_gathered = None cmd = ["/usr/bin/lintian", filename] (pid, stdin, stdout, stderr) = GLib.spawn_async(cmd, flags=GObject.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) for fd in [stdout, stderr]: channel = GLib.IOChannel(filedes=fd) channel.set_flags(GLib.IOFlags.NONBLOCK) GLib.io_add_watch(channel, GLib.PRIORITY_DEFAULT, GLib.IOCondition.IN | GLib.IO_ERR | GLib.IO_HUP, self._on_lintian_output) GLib.child_watch_add(GLib.PRIORITY_DEFAULT, pid, self._on_lintian_finished)
def generate_avi(self): folder_png = self.animation.get_png_dir() list_file = os.path.join(folder_png, "list") video_file = self.animation.get_avi_file() framerate = self.animation.get_framerate() if not os.path.exists(list_file): error_dlg = Gtk.MessageDialog( transient_for=self.dialog, title="Cannot continue", modal=True, destroy_with_parent=True, message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, text="In directory: %s there is no listing file" % (folder_png)) error_dlg.run() error_dlg.destroy() return if not self.converterpath: error_dlg = Gtk.MessageDialog( transient_for=self.dialog, title="Cannot continue", modal=True, destroy_with_parent=True, message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, text="Cannot find ffmpeg video conversion utility") error_dlg.run() error_dlg.destroy() return self.spinner.start() # calling ffmpeg # https://trac.ffmpeg.org/wiki/Concatenate # https://trac.ffmpeg.org/wiki/Encode/VP9 call = [ self.converterpath, "-nostdin", "-y", "-loglevel", "error", "-hide_banner", "-r", str(framerate), "-f", "concat", "-safe", "0", "-i", list_file ] if self.animation.get_redblue(): call.extend(["-vf", "colorchannelmixer=rr=0:rb=1:br=1:bb=0"]) call.extend([ "-c:v", "libvpx-vp9", "-crf", "30", "-b:v", "0", "-r", str(framerate), video_file ]) self.pid, fd_in, fd_out, fd_err = GLib.spawn_async( call, flags=GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=False, standard_error=True) self.fh_err = os.fdopen(fd_err, "r") GLib.child_watch_add(GLib.PRIORITY_DEFAULT, self.pid, self.video_complete) GLib.io_add_watch(self.fh_err, GLib.PRIORITY_DEFAULT, GLib.IOCondition.IN, self.video_error)
def on__main_revealer_button_clicked(self, button: Gtk.Button) -> None: operations: Dict[str, str] = self.settings.get_value('operations').unpack() folders_made: List[str] = self.settings.get_value( 'folders-made').unpack() for key, value in operations.items(): from_file: Gio.File = Gio.File.new_for_path(value) to_file: Gio.File = Gio.File.new_for_path(key) try: from_file.move(to_file, Gio.FileCopyFlags.NONE) except GLib.Error as err: print('%s: %s. (code: %s)' % (err.domain, err.message, err.code)) self.settings.reset('operations') for folder in folders_made: GLib.spawn_async(['/usr/bin/rm', '-r', folder]) self.settings.reset('folders-made')
def spawn_man_read(self): params = ['man', self.builder('entrycommandname').get_text()] def scroll_to_end(textview): i = textview.props.buffer.get_end_iter() mark = textview.props.buffer.get_insert() textview.props.buffer.place_cursor(i) textview.scroll_to_mark(mark, 0.0, True, 0.0, 1.0) def write_to_textview(io, condition, tw): if condition is GLib.IO_HUP: GLib.source_remove(self.source_id_out) GLib.source_remove(self.source_id_err) self.builder('spinner1').stop() return False line = io.readline() tw.props.buffer.insert_at_cursor(line) #time consumer, but good for attraction: #scroll_to_end(tw) while Gtk.events_pending(): Gtk.main_iteration_do(False) return True self.pid, stdin, stdout, stderr = GLib.spawn_async( params, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) self.builder('spinner1').start() io = GLib.IOChannel(stdout) err = GLib.IOChannel(stderr) self.source_id_out = io.add_watch(GLib.IO_IN | GLib.IO_HUP, write_to_textview, self.tw_out, priority=GLib.PRIORITY_HIGH) self.source_id_err = err.add_watch(GLib.IO_IN | GLib.IO_HUP, write_to_textview, self.tw_err, priority=GLib.PRIORITY_HIGH) timeout_id = GLib.timeout_add(100, self.update_progress) def closure_func(pid, status, data): GLib.spawn_close_pid(pid) GLib.source_remove(timeout_id) self.builder('spinner1').stop() self.pid = None GLib.child_watch_add(self.pid, closure_func, None)
def async_focus_on_window(window_id): window_id = hex(window_id) params = ["wmctrl", "-iR", window_id] pid, stdin, stdout, _ = \ GLib.spawn_async( params, flags=GLib.SpawnFlags.SEARCH_PATH|GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, standard_error=True)
def testChildWatch(self): self.data = None self.loop = GLib.MainLoop() argv = [sys.executable, '-c', 'import sys'] pid, stdin, stdout, stderr = GLib.spawn_async( argv, flags=GLib.SPAWN_DO_NOT_REAP_CHILD) pid.close() GLib.child_watch_add(pid, self._child_watch_cb, 12345) self.loop.run() self.assertEqual(self.data, 12345)
def spawn_async(argv, flags): _, pid = GLib.spawn_async( None, # Inherit current directory, argv, # Command with arguments. None, # Inherit environment. flags, None, # Child setup callback. None # User data. ) return pid
def test_spawn_async_envp(self): pid, stdin, stdout, stderr = GLib.spawn_async( ['sh', '-c', 'echo $TEST_VAR'], ['TEST_VAR=moo!'], flags=GLib.SpawnFlags.SEARCH_PATH, standard_output=True) self.assertEqual(stdin, None) self.assertEqual(stderr, None) out = os.read(stdout, 50) os.close(stdout) pid.close() self.assertEqual(out, b'moo!\n')
def _kill_selected_process(self, signal): pid = self._get_value_of_selected_row(self._COL_NR_PID) params = ["kill", "-{}".format(signal), str(pid)] pid, stdin, stdout, _ = \ GLib.spawn_async( params, flags=GLib.SpawnFlags.SEARCH_PATH|GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) self._async_update_task_liststore()
def process(self, widget, data=None): params = ['powershell',] def scroll_to_end(textview): i = textview.props.buffer.get_end_iter() mark = textview.props.buffer.get_insert() textview.props.buffer.place_cursor(i) textview.scroll_to_mark(mark, 0.0, True, 0.0, 1.0) def write_to_textview(io, condition, tw): if condition is GLib.IO_HUP: GLib.source_remove(self.source_id_out) GLib.source_remove(self.source_id_err) return False line = io.readline() tw.props.buffer.insert_at_cursor(line) scroll_to_end(tw) while Gtk.events_pending(): Gtk.main_iteration_do(False) return True self.pid, stdin, stdout, stderr = GLib.spawn_async(params, flags=GLib.SpawnFlags.SEARCH_PATH|GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, # standard_input=True, standard_error=True) self.progress.set_text('poweshell') io = GLib.IOChannel(stdout) err = GLib.IOChannel(stderr) self.source_id_out = io.add_watch(GLib.IO_IN|GLib.IO_HUP, write_to_textview, self.tw_out, priority=GLib.PRIORITY_HIGH) self.source_id_err = err.add_watch(GLib.IO_IN|GLib.IO_HUP, write_to_textview, self.tw_err, priority=GLib.PRIORITY_HIGH) timeout_id = GLib.timeout_add(100, self.update_progress) def closure_func(pid, status, data): GLib.spawn_close_pid(pid) GLib.source_remove(timeout_id) self.progress.set_fraction(0.0) GLib.child_watch_add(self.pid, closure_func, None)
def launch_detached(cmd): if use_systemd_run: cmd = ['systemd-run', '--user', '--scope'] + cmd env = dict(os.environ.items()) # Make sure GDK apps aren't forced to use x11 on wayland due to ulauncher's need to run # under X11 for proper centering. env.pop("GDK_BACKEND", None) try: envp = [f"{k}={v}" for k, v in env.items()] GLib.spawn_async( argv=cmd, envp=envp, flags=GLib.SpawnFlags.SEARCH_PATH_FROM_ENVP | GLib.SpawnFlags.SEARCH_PATH, # setsid is really only needed if systemd-run is missing, but doesn't hurt to have. child_setup=os.setsid) except Exception as e: logger.error('%s: %s', type(e).__name__, e)
def menu_activate_cb(self, menu, paths, remember=False): """Callback for menu item activation. If remembered is True, store the paths in self.remembered. Else lookup the comparator engine for that amount of paths and run it. The engine list is updated before. """ # remember only if remember: self.remembered = paths return # check for engine changes self.config.update_engines() # start comparison (if engine for that amount is still available) engine_cmd = [cp_utils.get_engine_for_amount(self.config, len(paths))] engine_cmd.extend(paths) if engine_cmd: flags = GLib.SpawnFlags.DEFAULT | GLib.SpawnFlags.SEARCH_PATH GLib.spawn_async(argv=engine_cmd, flags=flags)
def spawn_program(args, reply_handler, error_handler): """Spawn the program specified by 'args' using the GLib mainloop. When the program finishes, 'reply_handler' will be called with a single argument that will be the porgram status code. If there is an error, error_handler will be called with an instance of SpawnError. """ def child_watch(pid, status): """Handle child termination.""" # pylint: disable=E1103 GLib.spawn_close_pid(pid) # pylint: enable=E1103 if os.WIFEXITED(status): status = os.WEXITSTATUS(status) reply_handler(status) else: msg = 'Child terminated abnormally, '\ 'status from waitpid is %r' % status error_handler(msg=msg, failed_to_start=False) def handle_error(gerror): """Handle error when spawning the process.""" failed_to_start = NO_SUCH_FILE_OR_DIR in gerror.message msg = 'GError is: code %r, message %r' % (gerror.code, gerror.message) error_handler(msg=msg, failed_to_start=failed_to_start) flags = GLib.SpawnFlags.DO_NOT_REAP_CHILD | \ GLib.SpawnFlags.SEARCH_PATH | \ GLib.SpawnFlags.STDOUT_TO_DEV_NULL | \ GLib.SpawnFlags.STDERR_TO_DEV_NULL pid = None bytes_args = [] for arg in args: if isinstance(arg, compat.text_type): arg = arg.encode('utf-8') if not isinstance(arg, compat.basestring): arg = compat.binary_type(arg) bytes_args.append(arg) try: pid, _, _, _ = GLib.spawn_async(argv=bytes_args, flags=flags) except GLib.GError as e: handle_error(e) else: logger.debug('Spawning the program %r with the glib mainloop ' '(returned pid is %r).', args, pid) GLib.child_watch_add(pid, child_watch)
def test_spawn_async_fds(self): pid, stdin, stdout, stderr = GLib.spawn_async( ['cat'], flags=GLib.SpawnFlags.SEARCH_PATH, standard_input=True, standard_output=True, standard_error=True) os.write(stdin, b'hello world!\n') os.close(stdin) out = os.read(stdout, 50) os.close(stdout) err = os.read(stderr, 50) os.close(stderr) pid.close() self.assertEqual(out, b'hello world!\n') self.assertEqual(err, b'')
def __init__(self, argv, cb, *cb_data): self.Log.i('cmd = %s'%str(argv)) self.cmd = argv self.exited = False flags = (GLib.SPAWN_SEARCH_PATH | GLib.SPAWN_DO_NOT_REAP_CHILD) self.pid, stdin, stdout, stderr = GLib.spawn_async(argv, flags=flags) self.cb = cb self.cb_data = cb_data def cb(pid, status, ref): spawn = ref() if spawn: spawn.watch(pid, status) self.tag = GLib.child_watch_add(self.pid, cb, weakref.ref(self))
def process(self,widget,data=None): # changer le chemin de répertoire chemin = self.label_destination.get_text() print(chemin) os.chdir(chemin) # Pour l'instant on a besoin de 2 paramètres # Url et Format url = self.entree.get_text() format = self.combo.get_active_text() # On utlisera youtube-dl pour télécharger la vidéo params = ['youtube-dl','-f',format, url] def scroll_to_end(textview): i = textview.props.buffer.get_end_iter() mark = textview.props.buffer.get_insert() textview.props.buffer.place_cursor(i) textview.scroll_to_mark(mark, 0.0, True, 0.0, 1.0) def write_to_textview(io, condition, tw): if condition is GLib.IO_HUP: GLib.source_remove(self.source_id_out) GLib.source_remove(self.source_id_err) return False line = io.readline() tw.props.buffer.insert_at_cursor(line) scroll_to_end(tw) while Gtk.events_pending(): Gtk.main_iteration_do(False) return True self.pid, stdin, stdout, stderr = GLib.spawn_async(params,\ flags=GLib.SpawnFlags.SEARCH_PATH|GLib.SpawnFlags.DO_NOT_REAP_CHILD,\ standard_output=True,\ standard_error=True) io = GLib.IOChannel(stdout) err = GLib.IOChannel(stderr) self.source_id_out = io.add_watch(GLib.IO_IN|GLib.IO_HUP,\ write_to_textview,\ self.tw_out,\ priority=GLib.PRIORITY_HIGH) self.source_id_err = err.add_watch(GLib.IO_IN|GLib.IO_HUP,\ write_to_textview,\ self.tw_err,\ priority=GLib.PRIORITY_HIGH) timeout_id = GLib.timeout_add(100, self.update_progress) def closure_func(pid, status, data): GLib.spawn_close_pid(pid) GLib.source_remove(timeout_id) self.progress.set_fraction(0.0) GLib.child_watch_add(self.pid, closure_func, None)
def _activate_cb(self, menu, path): """ """ self._log.debug('acivate') napi_cmd = ['pynapi', '--tool-mode', path] self._log.debug('spawning command: %s', ' '.join(napi_cmd)) (pid, _, stdout, _) = GLib.spawn_async(napi_cmd, standard_output=True, flags=GLib.SpawnFlags.SEARCH_PATH|GLib.SPAWN_DO_NOT_REAP_CHILD) GLib.child_watch_add(pid, self._pynapi_finished, stdout, GLib.PRIORITY_DEFAULT) self._log.info('pynapi started as PID %d', pid)
def create_archive(self, files, callback): temp_dir = tempfile.mkdtemp("", "ffs-") if len(files) == 1: archive_name = os.path.join(temp_dir, GLib.path_get_basename(files[0])) else: archive_name = os.path.join(temp_dir, "archive.zip") cmd = ["7z", "-y", "-tzip", "-bd", "-mx=7", "a", archive_name] flags = GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD result = GLib.spawn_async(cmd + files, [], GLib.get_current_dir(), flags, None, None, False, True, False) self.out_7z = GLib.IOChannel(result[2]) self.out_7z.set_close_on_unref(True) GLib.child_watch_add(result[0], self.on_child_process_exit, callback) return archive_name
def spawn_async_raise(argv, workdir="."): """ A version of spawn_async that raises on error. raises SpawnError """ # FIXME: How to support locale strings? argv #argv = _argv_to_locale(argv) pretty.print_debug(__name__, "spawn_async", argv, workdir) try: return GLib.spawn_async (argv, working_directory=workdir, flags=GLib.SPAWN_SEARCH_PATH) except GLib.GError as exc: raise SpawnError(exc.message)
def test_child_watch_no_data(self): def cb(pid, status): self.status = status self.loop.quit() self.status = None self.loop = GLib.MainLoop() argv = [sys.executable, '-c', 'import sys'] pid, stdin, stdout, stderr = GLib.spawn_async( argv, flags=GLib.SpawnFlags.DO_NOT_REAP_CHILD) pid.close() id = GLib.child_watch_add(GLib.PRIORITY_HIGH, pid, cb) self.assertEqual(self.loop.get_context().find_source_by_id(id).priority, GLib.PRIORITY_HIGH) self.loop.run() self.assertEqual(self.status, 0)
def enabled(self): from gi.repository import GLib print_d("Starting %s" % self.PLUGIN_NAME) try: self._pid, fdin, fdout, fderr = GLib.spawn_async( argv=self.executable.split(), flags=GLib.SpawnFlags.SEARCH_PATH, standard_output=True, standard_input=True) except GLib.Error as e: msg = ((_("Couldn't run visualisations using '%s'") + " (%s)") % (escape(self.executable), escape(e.message))) ErrorMessage(title=_("Error"), description=msg, parent=app.window).run() else: # self._stdin = os.fdopen(fdin, mode='w') print_d("Launched with PID: %s" % self._pid)
def _vmUpOperation(self): assert self.vmPid is None dbusObj = dbus.SystemBus().get_object('org.fpemud.VirtService', '/org/fpemud/VirtService') try: self.maxDriveId = 0 self.vmTmpDir = tempfile.mkdtemp(prefix="lightbox.vm.") self.vsVmResSetId = dbusObj.NewVmResSet(dbus_interface='org.fpemud.VirtService') resSetObj = dbus.SystemBus().get_object('org.fpemud.VirtService', '/org/fpemud/VirtService/%d/VmResSets/%d' % (os.getuid(), self.vsVmResSetId)) if self.vmCfg.networkAdapterInterface == "virtio": # resSetObj.AddTapIntf(self.vmEnv.getVirtioNetworkType()) resSetObj.AddTapIntf("nat", dbus_interface='org.fpemud.VirtService.VmResSet') self.vsVmId = dbusObj.AttachVm(self.vmDir, self.vsVmResSetId, dbus_interface='org.fpemud.VirtService') self.vsTapIfName = resSetObj.GetTapIntf(dbus_interface='org.fpemud.VirtService.VmResSet') self.vsMacAddr = resSetObj.GetVmMacAddr(dbus_interface='org.fpemud.VirtService.VmResSet') self.vsIpAddr = resSetObj.GetVmIpAddr(dbus_interface='org.fpemud.VirtService.VmResSet') self.spicePort = FvpUtil.getFreeSocketPort("tcp", self.param.spicePortStart, self.param.spicePortEnd) self.qmpPort = FvpUtil.getFreeSocketPort("tcp") qemuCmd = self._generateQemuCommand() mycwd = os.getcwd() os.chdir(self.vmDir) try: targc, targv = GLib.shell_parse_argv(qemuCmd) ret = GLib.spawn_async(targv, flags=GLib.SpawnFlags.DO_NOT_REAP_CHILD) self.vmPid = ret[0] self.vmPidWatch = GLib.child_watch_add(self.vmPid, self.onVmExit) time.sleep(1) # fixme: should change fvp_vm_view, repeat connect finally: os.chdir(mycwd) self.qmpObj = qmp.QmpClient() self.qmpObj.connect_tcp("127.0.0.1", self.qmpPort) self.state = FvpVmObject.STATE_POWER_ON self.notify("state") except: self._vmDownOperation(True, dbusObj) raise
def spawn(argv, stdout=False): """Asynchronously run a program. argv[0] is the executable name, which must be fully qualified or in the path. If stdout is True, return a file object corresponding to the child's standard output; otherwise, return the child's process ID. argv must be strictly str objects to avoid encoding confusion. """ from gi.repository import GLib print_d("Running %r" % argv) args = GLib.spawn_async(argv=argv, flags=GLib.SpawnFlags.SEARCH_PATH, standard_output=stdout) if stdout: return os.fdopen(args[2]) else: return args[0]
def _run_lintian(self, filename): buf = self.textview_lintian_output.get_buffer() if not os.path.exists("/usr/bin/lintian"): buf.set_text( _("No lintian available.\n" "Please install using sudo apt-get install lintian")) return buf.set_text(_("Running lintian...")) self._lintian_output = "" self._lintian_exit_status = None cmd = ["/usr/bin/lintian", filename] (pid, stdin, stdout, stderr) = GLib.spawn_async( cmd, flags=GObject.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) for fd in [stdout, stderr]: channel = GLib.IOChannel(filedes=fd) channel.set_flags(GLib.IOFlags.NONBLOCK) channel.add_watch(GLib.IOCondition.IN, self._on_lintian_output) GObject.child_watch_add( pid, self._on_lintian_finished)
def _check_for_channel_updates_timer(self): """ run a background timer to see if the a-x-i data we have is still fresh or if the cache has changed since """ # this is expensive and does not need UI to we shove it out channel_update = os.path.join( softwarecenter.paths.datadir, "update-software-center-channels") (pid, stdin, stdout, stderr) = GLib.spawn_async( [channel_update], flags=GLib.SpawnFlags.DO_NOT_REAP_CHILD) # python-gobject >= 3.7.3 has changed some API in incompatible # ways, so we need to check the version for which one to use. if gi_version < (3, 7, 3): GLib.child_watch_add(pid, self._on_check_for_channel_updates_finished) else: GLib.child_watch_add(GLib.PRIORITY_DEFAULT, pid, self._on_check_for_channel_updates_finished)
def run_software_center_agent(db): """ Helper that triggers the update-software-center-agent helper and will also reopen the database on success """ def _on_update_software_center_agent_finished(pid, condition): LOG.info("software-center-agent finished with status %i" % os.WEXITSTATUS(condition)) if os.WEXITSTATUS(condition) == 0: db.reopen() # run the update sc_agent_update = os.path.join(softwarecenter.paths.datadir, "update-software-center-agent") (pid, stdin, stdout, stderr) = GLib.spawn_async( [sc_agent_update, "--datadir", softwarecenter.paths.datadir], flags=GObject.SPAWN_DO_NOT_REAP_CHILD ) # python-gobject >= 3.7.3 has changed some API in incompatible # ways, so we need to check the version for which one to use. if gi_version < (3, 7, 3): GLib.child_watch_add(pid, _on_update_software_center_agent_finished) else: GLib.child_watch_add(GLib.PRIORITY_DEFAULT, pid, _on_update_software_center_agent_finished)
def _async_update_task_liststore(self): params = ["wmctrl", "-lpx"] pid, stdin, stdout, _ = GLib.spawn_async(params, flags=GLib.SpawnFlags.SEARCH_PATH|GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) io = GLib.IOChannel(stdout) def parse_wlist_output(wlist_output): windows = list() for line in wlist_output.splitlines(): xid, line = line.split(" ", 1) line = line.lstrip() desktop_id, line = line.split(" ", 1) del desktop_id line = line.lstrip() pid, line = line.split(" ", 1) pid = int(pid) line = line.lstrip() wm_class, line = line.split(" ", 1) if wm_class == "N/A": continue line = line.lstrip() hostname, line = line.split(" ", 1) del hostname title = line.lstrip() if title == "Desktop": continue window = [xid, pid, wm_class, title] windows.append(window) return windows def wlist_finish_callback(*args, **kwargs): wlist_output = io.read() windows = parse_wlist_output(wlist_output) self._update_task_liststore_callback(windows) self.source_id_out = io.add_watch(GLib.IO_IN|GLib.IO_HUP, wlist_finish_callback, priority=GLib.PRIORITY_HIGH)
def spawn(argv, stdout=False): """Asynchronously run a program. argv[0] is the executable name, which must be fully qualified or in the path. If stdout is True, return a file object corresponding to the child's standard output; otherwise, return the child's process ID. argv must be strictly str objects to avoid encoding confusion. """ from gi.repository import GLib # NOQA types = map(type, argv) if not (min(types) == max(types) == str): raise TypeError("executables and arguments must be str objects") logger.debug("Running %r" % " ".join(argv)) args = GLib.spawn_async(argv=argv, flags=GLib.SpawnFlags.SEARCH_PATH, standard_output=stdout) if stdout: return os.fdopen(args[2]) else: return args[0]
def start_session(self, host, port, session, username, password, wait): """ Start a session using x2go """ # Start in the background and attach a watch for when it exits cmd = [os.path.join(softwarecenter.paths.datadir, softwarecenter.paths.X2GO_HELPER)] (self.helper_pid, stdin, stdout, stderr) = GLib.spawn_async( cmd, standard_input=True, standard_output=True, standard_error=True, flags=GObject.SPAWN_DO_NOT_REAP_CHILD) self.helper_stdin = os.fdopen(stdin, "w") self.helper_stdout = os.fdopen(stdout) self.helper_stderr = os.fdopen(stderr) # Add a watch for when the process exits GLib.child_watch_add( GLib.PRIORITY_DEFAULT, self.helper_pid, self._on_x2go_exit) # Add a watch on stdout channel = GLib.IOChannel.unix_new(self.helper_stdout) GLib.io_add_watch(channel, GLib.PRIORITY_DEFAULT, GObject.IO_IN, self._on_x2go_activity) # Start the connection self.state = "connecting" self.helper_stdin.write( "CONNECT: \"%s\" \"%s\" \"%s\" \"%s\" \"%s\"\n" % (host, port, username, password, session)) self.helper_stdin.flush()