def run(self, line=1, column=1): dirname = os.path.dirname(self.filename) filename = os.path.basename(self.filename) self.ret = None try: self.pipe = subprocess.Popen( ['cdn-context', filename, '-l', str(line), '-c', str(column)], cwd=dirname, stdout=subprocess.PIPE) except Exception as (e): sys.stderr.write('Failed to execute cdn-context: %s\n' % (e, )) self.pipe = None return False self.read_buffer = '' flags = fcntl.fcntl(self.pipe.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK fcntl.fcntl(self.pipe.stdout.fileno(), fcntl.F_SETFL, flags) GObject.io_add_watch(self.pipe.stdout, GObject.IO_IN | GObject.IO_HUP, self.on_output) GObject.child_watch_add(self.pipe.pid, self.on_parser_end)
def __init__(self, handle): # fork pygame before we initialize the activity. pygame.init() windowid = pygame.display.get_wm_info()['wmwindow'] self.child_pid = os.fork() if self.child_pid == 0: library_path = os.path.join(activity.get_bundle_path(), 'library') app_path = os.path.join(activity.get_bundle_path(), 'app.py') sys.path[0:0] = [library_path] g = globals() g['__name__'] = '__main__' execfile(app_path, g, g) # start pygame sys.exit(0) super(PyGameActivity, self).__init__(handle) toolbarbox = ToolbarBox() self.set_toolbar_box(toolbarbox) toolbar = toolbarbox.toolbar socket = Gtk.Socket() socket.set_can_focus(True) socket.add_id(windowid) self.set_canvas(socket) self.show_all() socket.grab_focus() GObject.child_watch_add(self.child_pid, lambda pid, cond: self.close())
def attach(self, options=None): logging.info('starting kodi') self.main.expect_stop = False if self.status() == 1: return if self.shutdown_inhibitor: try: # Shutdown inhibitor self.inhibitor = self.main.inhibit( what="shutdown:sleep:idle", who="frontend", why="kodi running", mode="block" ) except: logging.warning("could not set shutdown-inhobitor") try: self.proc = subprocess.Popen(self.cmd, env=os.environ) if self.proc: self.block = True if self.proc.poll() is not None: logging.warning("failed to start kodi") self.main.switchFrontend() # Add callback on exit GObject.child_watch_add(self.proc.pid, self.on_exit, self.proc) logging.debug('started kodi') except: logging.exception('could not start kodi') return False return True
def __init__(self, handle): # fork pygame before we initialize the activity. pygame.init() windowid = pygame.display.get_wm_info()['wmwindow'] self.child_pid = os.fork() if self.child_pid == 0: library_path = os.path.join(activity.get_bundle_path(), 'library') app_path = os.path.join(activity.get_bundle_path(), 'app.py') sys.path[0:0] = [library_path] g = globals() g['__name__'] = '__main__' execfile(app_path, g, g) # start pygame sys.exit(0) super(PyGameActivity, self).__init__(handle) toolbarbox = ToolbarBox() self.set_toolbar_box(toolbarbox) toolbar = toolbarbox.toolbar socket = Gtk.Socket() socket.set_can_focus(True) socket.add_id(windowid) self.set_canvas(socket) self.show_all() socket.grab_focus() GObject.child_watch_add(self.child_pid, lambda pid, cond: self.close())
def attach(self, options=None): logging.debug('starting xine') logging.debug('self.cmd') self.proc = subprocess.Popen("exec " + self.cmd, shell=True, env=os.environ) GObject.child_watch_add(self.proc.pid,self.on_exit,self.proc) # Add callback on exit logging.debug('started xine')
def do_spawn_async(event): self.pid, stdin, stdout, stderr = GObject.spawn_async( argv, working_directory=chdir, child_setup=self.__setup, standard_input=True, standard_output=True, standard_error=True, flags=GObject.SPAWN_DO_NOT_REAP_CHILD | GObject.SPAWN_SEARCH_PATH) log.debug("SubProcess.__init__: _initChannel...", extra={"task": self.defname}) self.__channelTags = [] self.inChannel = self._initChannel(stdin, None, None, False) readFlags = GObject.IO_IN | GObject.IO_HUP #|GObject.IO_ERR self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb, False) self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb, True) log.debug("SubProcess.__init__: channelsClosed...", extra={"task": self.defname}) self.channelsClosed = False self.channelsClosedLock = threading.Lock() log.debug("SubProcess.__init__: child_watch_add...", extra={"task": self.defname}) GObject.child_watch_add(self.pid, self.__child_watch_callback, None) if event is not None: event.set()
def __init__(self, handle): # fork pygame before we initialize the activity. import os import pygame import sys pygame.init() windowid = pygame.display.get_wm_info()['wmwindow'] self.child_pid = os.fork() if self.child_pid == 0: bp = activity.get_bundle_path() library_path = os.path.join(bp, 'library') pippy_app_path = os.path.join(bp, 'pippy_app.py') sys.path[0:0] = [library_path] g = globals() g['__name__'] = '__main__' execfile(pippy_app_path, g, g) # start pygame sys.exit(0) super(PyGameActivity, self).__init__(handle) from gi.repository import GObject from gi.repository import Gtk toolbox = activity.ActivityToolbox(self) toolbar = toolbox.get_activity_toolbar() self.set_toolbox(toolbox) toolbox.show() socket = Gtk.Socket() socket.set_flags(socket.flags() | Gtk.CAN_FOCUS) socket.show() self.set_canvas(socket) socket.add_id(windowid) self.show_all() socket.grab_focus() GObject.child_watch_add(self.child_pid, lambda pid, cond: self.close()) # hide the buttons we don't use. toolbar.share.hide() # this should share bundle. toolbar.keep.hide()
def attach(self, options=None): logging.info('starting xbmc') self.main.expect_stop = False if self.status() == 1: return if self.shutdown_inhibitor: try: # Shutdown inhibitor self.inhibitor = self.main.inhibit(what="shutdown:sleep:idle", who="frontend", why="xbmc running", mode="block") except: logging.warning("could not set shutdown-inhobitor") try: self.proc = subprocess.Popen(self.cmd, env=os.environ) if self.proc: self.block = True if self.proc.poll() is not None: logging.warning("failed to start xbmc") self.main.switchFrontend() # Add callback on exit GObject.child_watch_add(self.proc.pid, self.on_exit, self.proc) logging.debug('started xbmc') except: logging.exception('could not start xbmc') return False return 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) = GObject.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 GObject.child_watch_add(self.helper_pid, self._on_x2go_exit) # Add a watch on stdout GObject.io_add_watch(self.helper_stdout, 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 spawn(command, system=False, sn=None, reap=True, *args, **kwargs): def child_closed(pid, cond): dprint(command, "closed") if sn: sn.complete() if not system: if type(command) == list: command[0] = os.path.join(BIN_DIR, command[0]) else: command = os.path.join(BIN_DIR, command) else: if type(command) == list: command[0] = os.path.expanduser(command[0]) else: command = os.path.expanduser(command) env = os.environ if sn: id = sn.get_startup_id() env["DESKTOP_STARTUP_ID"] = id env["BLUEMAN_EVENT_TIME"] = str(Gtk.get_current_event_time()) p = Popen(command, env=env, *args, **kwargs) if reap: GObject.child_watch_add(p.pid, child_closed) return p
def _create_activity(self): if self._handle.activity_id is None: self._handle.activity_id = create_activity_id() self._shell.NotifyLaunch( self._service_name, self._handle.activity_id, reply_handler=self._no_reply_handler, error_handler=self._notify_launch_error_handler) environ = get_environment(self._bundle) (log_path, log_file) = open_log_file(self._bundle) command = get_command(self._bundle, self._handle.activity_id, self._handle.object_id, self._handle.uri, self._handle.invited) dev_null = file('/dev/null', 'r') child = subprocess.Popen([str(s) for s in command], env=environ, cwd=str(self._bundle.get_path()), close_fds=True, stdin=dev_null.fileno(), stdout=log_file.fileno(), stderr=log_file.fileno()) GObject.child_watch_add(child.pid, _child_watch_cb, (log_file, self._handle.activity_id))
def start_session(self, host, port, session, username, password, wait): """ Start a session using qtnx """ self.state = "connecting" if not os.path.exists(os.path.expanduser('~/.qtnx')): os.mkdir(os.path.expanduser('~/.qtnx')) # Generate qtnx's configuration file filename = os.path.expanduser('~/.qtnx/%s-%s-%s.nxml') % ( host, port, session.replace("/", "_")) nxml = open(filename, "w+") config = self.NXML_TEMPLATE config = config.replace("WL_NAME", "%s-%s-%s" % (host, port, session.replace("/", "_"))) config = config.replace("WL_SERVER", host) config = config.replace("WL_PORT", str(port)) config = config.replace("WL_COMMAND", "weblive-session %s" % session) nxml.write(config) nxml.close() # Prepare qtnx call cmd = [self.BINARY_PATH, '%s-%s-%s' % (str(host), str(port), session.replace("/", "_")), username, password] def qtnx_countdown(): """ Send progress events every two seconds """ if self.helper_progress == 10: self.state = "connected" self.emit("connected", False) return False else: self.emit("progress", self.helper_progress * 10) self.helper_progress += 1 return True def qtnx_start_timer(): """ As we don't have a way of knowing the connection status, we countdown from 20s """ self.helper_progress = 0 qtnx_countdown() GObject.timeout_add_seconds(2, qtnx_countdown) qtnx_start_timer() if wait == False: # Start in the background and attach a watch for when it exits (self.helper_pid, stdin, stdout, stderr) = GObject.spawn_async( cmd, standard_input=True, standard_output=True, standard_error=True, flags=GObject.SPAWN_DO_NOT_REAP_CHILD) GObject.child_watch_add(self.helper_pid, self._on_qtnx_exit, filename) else: # Start it and wait till it finishes p = subprocess.Popen(cmd) p.wait()
def _create_activity(self): if self._handle.activity_id is None: self._handle.activity_id = create_activity_id() self._shell.NotifyLaunch( self._service_name, self._handle.activity_id, reply_handler=self._no_reply_handler, error_handler=self._notify_launch_error_handler) environ = get_environment(self._bundle) (log_path, log_file) = open_log_file(self._bundle) command = get_command(self._bundle, self._handle.activity_id, self._handle.object_id, self._handle.uri, self._handle.invited) dev_null = file('/dev/null', 'r') child = subprocess.Popen([str(s) for s in command], env=environ, cwd=str(self._bundle.get_path()), close_fds=True, stdin=dev_null.fileno(), stdout=log_file.fileno(), stderr=log_file.fileno()) GObject.child_watch_add(child.pid, _child_watch_cb, (log_file, self._handle.activity_id))
def __init__(self, path, args=[], warnwords=[], env=None, chdir="."): GObject.GObject.__init__(self) self.path = path self.args = args self.warnwords = warnwords self.env = env or os.environ self.buffer = "" self.linePublisher = EmitPublisher(self, "line", 'SubProcess.linePublisher', EmitPublisher.SEND_LIST) self.linePublisher.start() self.defname = os.path.split(path)[1] self.defname = self.defname[:1].upper() + self.defname[1:].lower() t = time.time() self.defname = (self.defname, time.strftime("%H:%m:%%.3f", time.localtime(t)) % (t % 60)) log.debug(path, extra={"task": self.defname}) argv = [str(u) for u in [self.path] + self.args] log.debug("SubProcess.__init__: spawning...", extra={"task": self.defname}) self.pid, stdin, stdout, stderr = GObject.spawn_async( argv, working_directory=chdir, child_setup=self.__setup, standard_input=True, standard_output=True, standard_error=True, flags=GObject.SPAWN_DO_NOT_REAP_CHILD | GObject.SPAWN_SEARCH_PATH) log.debug("SubProcess.__init__: _initChannel...", extra={"task": self.defname}) self.__channelTags = [] self.inChannel = self._initChannel(stdin, None, None, False) readFlags = GObject.IO_IN | GObject.IO_HUP #|GObject.IO_ERR self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb, False) self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb, True) log.debug("SubProcess.__init__: channelsClosed...", extra={"task": self.defname}) self.channelsClosed = False self.channelsClosedLock = threading.Lock() log.debug("SubProcess.__init__: child_watch_add...", extra={"task": self.defname}) GObject.child_watch_add(self.pid, self.__child_watch_callback) log.debug("SubProcess.__init__: subprocExitCode...", extra={"task": self.defname}) self.subprocExitCode = (None, None) self.subprocFinishedEvent = threading.Event() subprocesses.append(self) log.debug("SubProcess.__init__: finished", extra={"task": self.defname})
def spawn(command, system=False, sn=None, reap=True, *args, **kwargs): def child_closed(pid, cond): dprint(command, "closed") if sn: sn.complete() if not system: if type(command) == list: command[0] = os.path.join(BIN_DIR, command[0]) else: command = os.path.join(BIN_DIR, command) else: if type(command) == list: command[0] = os.path.expanduser(command[0]) else: command = os.path.expanduser(command) env = os.environ if sn: id = sn.get_startup_id() env["DESKTOP_STARTUP_ID"] = id env["BLUEMAN_EVENT_TIME"] = str(Gtk.get_current_event_time()) p = Popen(command, env=env, *args, **kwargs) if reap: GObject.child_watch_add(p.pid, child_closed) return p
def attach(self, options=None): if self.mode == 'remote' and self.status() == 0: while not self.isOpen(): time.sleep(1) logging.info('starting vdr-sxfe') self.proc = subprocess.Popen("exec " + self.cmd, shell=True, env=os.environ) GObject.child_watch_add(self.proc.pid, self.on_exit, self.proc) # Add callback on exit if self.proc: self.block = True logging.debug('started vdr-sxfe') if self.proc.poll() is not None: logging.warning("failed to start vdr-sxfe") return False else: logging.debug('vdr-sxfe is still running') self.state = 1 return True elif self.mode == 'local' and self.status() == 0: self.main.dbus2vdr.Plugins.SVDRPCommand('xinelibputput', 'LFRO', 'sxfe') self.state = 1 return True
def __init__(self, handle): # fork pygame before we initialize the activity. import os import pygame import sys pygame.init() windowid = pygame.display.get_wm_info()['wmwindow'] self.child_pid = os.fork() if self.child_pid == 0: bp = activity.get_bundle_path() library_path = os.path.join(bp, 'library') pippy_app_path = os.path.join(bp, 'pippy_app.py') sys.path[0:0] = [library_path] g = globals() g['__name__'] = '__main__' execfile(pippy_app_path, g, g) # start pygame sys.exit(0) super(PyGameActivity, self).__init__(handle) from gi.repository import GObject from gi.repository import Gtk toolbox = activity.ActivityToolbox(self) toolbar = toolbox.get_activity_toolbar() self.set_toolbox(toolbox) toolbox.show() socket = Gtk.Socket() socket.set_flags(socket.flags() | Gtk.CAN_FOCUS) socket.show() self.set_canvas(socket) socket.add_id(windowid) self.show_all() socket.grab_focus() GObject.child_watch_add(self.child_pid, lambda pid, cond: self.close()) # hide the buttons we don't use. toolbar.share.hide() # this should share bundle. toolbar.keep.hide()
def attach(self, options=None): logging.info('starting xbmc') if self.status() == 1: return try: # Shutdown inhibitor self.inhibitor = self.main.inhibit( what="shutdown:sleep:idle", who="frontend", why="xbmc running", mode="block" ) except: logging.warning("could not set shutdown-inhobitor") try: self.proc = subprocess.Popen("exec " + self.cmd, shell=True, env=self.environ) if self.proc: self.block = True if self.proc.poll() is not None: logging.warning("failed to start xbmc") self.main.switchFrontend() GObject.child_watch_add(self.proc.pid,self.on_exit,self.proc) # Add callback on exit logging.debug('started xbmc') except: logging.exception('could not start xbmc')
def do_spawn_async(event): flags = GLib.SPAWN_DO_NOT_REAP_CHILD|GLib.SPAWN_SEARCH_PATH if sys.platform == "win32": flags |= GLib.SPAWN_WIN32_HIDDEN_CONSOLE self.pid, stdin, stdout, stderr = GObject.spawn_async(argv, working_directory=chdir, child_setup=self.__setup, standard_input=True, standard_output=True, standard_error=True, flags=flags) log.debug("SubProcess.__init__: _initChannel...", extra={"task":self.defname}) self.__channelTags = [] self.inChannel = self._initChannel(stdin, None, None, False) readFlags = GObject.IO_IN|GObject.IO_HUP#|GObject.IO_ERR self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb, False) self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb, True) log.debug("SubProcess.__init__: channelsClosed...", extra={"task":self.defname}) self.channelsClosed = False self.channelsClosedLock = threading.Lock() log.debug("SubProcess.__init__: child_watch_add...", extra={"task":self.defname}) # On Python3 pygobject versions before 3.10.0 spawn_async returns pid as 0 # see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=712537 if self.pid != 0: GObject.child_watch_add(self.pid, self.__child_watch_callback, None) if event is not None: event.set()
def spawn(self, args=None, callback=None, data=None, cwd=None): '''Start the application in the background and return immediately. This is used to start an external in parallel with zim that is not expected to exit immediatly, so we do not want to wait for it - e.g. a webbrowser to show an URL that was clicked. @param args: additional arguments to give to the command as tuple or list @param callback: optional callback can be used to trigger when the application exits. The signature is:: callback(status, data) where 'C{status}' is the exit status of the process. The application object provides a constant 'C{STATUS_OK}' which can be used to test if the application was successful or not. @param data: additional data for the callback @param cwd: the folder to set as working directory for the command @returns: the PID for the new process ''' cwd, argv = self._checkargs(cwd, args) opts = {} flags = GObject.SPAWN_SEARCH_PATH if callback: flags |= GObject.SPAWN_DO_NOT_REAP_CHILD # without this flag child is reaped automatically -> no zombies logger.info('Spawning: %s (cwd: %s)', argv, cwd) if TEST_MODE: TEST_MODE_RUN_CB(argv) return None try: try: pid, stdin, stdout, stderr = \ GObject.spawn_async(argv, flags=flags, **opts) except GObject.GError: if _CAN_CALL_FLATPAK_HOST_COMMAND: pid, stdin, stdout, stderr = \ GObject.spawn_async(_FLATPAK_HOSTCOMMAND_PREFIX + argv, flags=flags, **opts) else: raise except GObject.GError: from zim.gui.widgets import ErrorDialog ErrorDialog(None, _('Failed running: %s') % argv[0]).run() #~ # T: error when application failed to start return None else: logger.debug('Process started with PID: %i', pid) if callback: # child watch does implicit reaping -> no zombies if data is None: GObject.child_watch_add( pid, lambda pid, status: callback(status)) else: GObject.child_watch_add( pid, lambda pid, status, data: callback(status, data), data) return pid
def spawn_process(self): os.chdir(os.path.expanduser('~')) self.ps = Popen(shlex.split(conf.get(self.name, 'Command')), stdout=PIPE, stdin=PIPE) self.pid = self.ps.pid GObject.child_watch_add(self.pid, self.on_child_exit, self) GObject.timeout_add(100, self._search_window)
def manage_script(self, address, node, process): if not address in self.scripts: self.scripts[address] = {} if node in self.scripts[address]: self.scripts[address][node].terminate() self.scripts[address][node] = process GObject.child_watch_add(process.pid, self.on_script_closed, (address, node))
def manage_script(self, address, node, process): if not address in self.scripts: self.scripts[address] = {} if node in self.scripts[address]: self.scripts[address][node].terminate() self.scripts[address][node] = process GObject.child_watch_add(process.pid, self.on_script_closed, (address, node))
def SetGN(self, enabled, caller): self.timer.reset() if enabled: p = subprocess.Popen(["/usr/sbin/avahi-autoipd", "-D", "pan0"], env=os.environ, bufsize=128) else: p = subprocess.Popen(["/usr/sbin/avahi-autoipd", "-k", "pan0"], bufsize=128) #reap the child GObject.child_watch_add(p.pid, lambda pid, cond: 0)
def attach(self, options=None): logging.debug('starting xine') logging.debug('self.cmd') self.proc = subprocess.Popen("exec " + self.cmd, shell=True, env=os.environ) GObject.child_watch_add(self.proc.pid, self.on_exit, self.proc) # Add callback on exit logging.debug('started xine')
def _create_activity(self): if self._handle.activity_id is None: self._handle.activity_id = create_activity_id() self._shell.NotifyLaunch( self._service_name, self._handle.activity_id, reply_handler=self._no_reply_handler, error_handler=self._notify_launch_error_handler) environ = get_environment(self._bundle) (log_path, log_file) = open_log_file(self._bundle) command = get_command(self._bundle, self._handle.activity_id, self._handle.object_id, self._handle.uri, self._handle.invited) dev_null = file('/dev/null', 'w') environment_dir = None rainbow_found = subprocess.call(['which', 'rainbow-run'], stdout=dev_null, stderr=dev_null) == 0 use_rainbow = rainbow_found and os.path.exists('/etc/olpc-security') if use_rainbow: environment_dir = tempfile.mkdtemp() command = ['sudo', '-E', '--', 'rainbow-run', '-v', '-v', '-a', 'rainbow-sugarize', '-s', '/var/spool/rainbow/2', '-f', '1', '-f', '2', '-c', self._bundle.get_path(), '-u', pwd.getpwuid(os.getuid()).pw_name, '-i', environ['SUGAR_BUNDLE_ID'], '-e', environment_dir, '--', ] + command for key, value in environ.items(): file_path = os.path.join(environment_dir, str(key)) open(file_path, 'w').write(str(value)) log_file.write(' '.join(command) + '\n\n') dev_null = file('/dev/null', 'r') child = subprocess.Popen([str(s) for s in command], env=environ, cwd=str(self._bundle.get_path()), close_fds=True, stdin=dev_null.fileno(), stdout=log_file.fileno(), stderr=log_file.fileno()) GObject.child_watch_add(child.pid, _child_watch_cb, (environment_dir, log_file, self._handle.activity_id))
def attach(self, options=None): if self.mode == 'remote' and self.status() == 0: while not self.isOpen(): time.sleep(1) logging.info('starting vdr-sxfe') self.proc = subprocess.Popen("exec " + self.cmd,shell=True,env=self.environ) GObject.child_watch_add(self.proc.pid,self.on_exit,self.proc) # Add callback on exit logging.debug('started vdr-sxfe') elif self.mode == 'local' and self.status() == 0: self.main.dbus2vdr.Plugins.SVDRPCommand('xinelibputput', 'LFRO', 'sxfe') self.state = 1
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) = GObject.spawn_async( [channel_update], flags=GObject.SPAWN_DO_NOT_REAP_CHILD) GObject.child_watch_add( pid, self._on_check_for_channel_updates_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) = GObject.spawn_async([channel_update], flags=GObject.SPAWN_DO_NOT_REAP_CHILD) GObject.child_watch_add(pid, self._on_check_for_channel_updates_finished)
def __init__(self, handle): # fork pygame before we initialize the activity. import os import pygame import sys pygame.init() windowid = pygame.display.get_wm_info()['wmwindow'] self.child_pid = os.fork() if self.child_pid == 0: bp = activity.get_bundle_path() library_path = os.path.join(bp, 'library') pippy_app_path = os.path.join(bp, 'pippy_app.py') sys.path[0:0] = [library_path] g = globals() g['__name__'] = '__main__' execfile(pippy_app_path, g, g) # start pygame sys.exit(0) super(PyGameActivity, self).__init__(handle) from gi.repository import GObject from gi.repository import Gtk self.max_participants = 1 # no sharing toolbox = ToolbarBox() activity_button_toolbar = ActivityToolbarButton(self) toolbox.toolbar.insert(activity_button_toolbar, 0) activity_button_toolbar.show() self.set_toolbar_box(toolbox) toolbox.show() separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) toolbox.toolbar.insert(separator, -1) separator.show() stop_button = StopButton(self) stop_button.props.accelerator = '<Ctrl>q' toolbox.toolbar.insert(stop_button, -1) stop_button.show() toolbox.toolbar.show_all() socket = Gtk.Socket() socket.set_flags(socket.flags() | Gtk.CAN_FOCUS) socket.show() self.set_canvas(socket) socket.add_id(windowid) self.show_all() socket.grab_focus() GObject.child_watch_add(self.child_pid, lambda pid, cond: self.close())
def ipc_pipe_based(self, mseconds = 0): assert hasattr (self, 'cmd') and hasattr (self, 'callback') pid, _, stdout, stderr = self.__run_spawn_async() if mseconds > 0: timeout_id = GObject.timeout_add (mseconds, self.kill, pid) def callback_parser (*args): with io.open(stdout) as out, io.open(stderr) as err: self.callback((args[1] >> 8) & 0xFF, out.read()) self.__error_parser (err.read()) if mseconds > 0: GObject.source_remove (timeout_id) GObject.child_watch_add (pid, callback_parser)
def _run_synaptic(self, action, opt, tempf): """Execute synaptic.""" try: apt_pkg.pkgsystem_unlock() except SystemError: pass cmd = ["/usr/bin/gksu", "--desktop", "/usr/share/applications/update-manager.desktop", "--", "/usr/sbin/synaptic", "--hide-main-window", "--non-interactive", "--parent-window-id", "%s" % self.window_main.window.xid ] cmd.extend(opt) flags = GObject.SPAWN_DO_NOT_REAP_CHILD (pid, stdin, stdout, stderr) = GObject.spawn_async(cmd, flags=flags) GObject.child_watch_add(pid, self._on_synaptic_exit, (action, tempf))
def run (self, mseconds = 0): assert hasattr (self, 'cmd') and hasattr (self, 'callback') and hasattr (self, 'writer') pid, _, stdout, stderr = self.__run_spawn_async() GObject.io_add_watch (stdout, GObject.IO_IN, self.writer) if mseconds > 0: timeout_id = GObject.timeout_add (mseconds, self.kill, pid) def callback_runner (*args): self.callback() with io.open(stderr) as err: self.__error_parser (err.read()) if mseconds > 0: GObject.source_remove (timeout_id) GObject.child_watch_add (pid, callback_runner) return pid
def _run_synaptic(self, action, opt, tempf): """Execute synaptic.""" try: apt_pkg.pkgsystem_unlock() except SystemError: pass cmd = ["/usr/bin/pkexec", "/usr/sbin/synaptic", "--hide-main-window", "--non-interactive", "--parent-window-id", "%s" % self.window_main.get_window().get_xid() ] cmd.extend(opt) flags = GObject.SPAWN_DO_NOT_REAP_CHILD (pid, stdin, stdout, stderr) = GObject.spawn_async(cmd, flags=flags) # Keep a reference to the data tuple passed to # GObject.child_watch_add to avoid attempts to destroy it without a # thread context: https://bugs.launchpad.net/bugs/724687 self.child_data = (action, tempf) GObject.child_watch_add(pid, self._on_synaptic_exit, self.child_data)
def __init__(self, path, args=[], warnwords=[], env=None, chdir="."): GObject.GObject.__init__(self) self.path = path self.args = args self.warnwords = warnwords self.env = env or os.environ self.buffer = "" self.linePublisher = EmitPublisher(self, "line", 'SubProcess.linePublisher', EmitPublisher.SEND_LIST) self.linePublisher.start() self.defname = os.path.split(path)[1] self.defname = self.defname[:1].upper() + self.defname[1:].lower() t = time.time() self.defname = (self.defname, time.strftime("%H:%m:%%.3f",time.localtime(t)) % (t%60)) log.debug(path, extra={"task":self.defname}) argv = [str(u) for u in [self.path]+self.args] log.debug("SubProcess.__init__: spawning...", extra={"task":self.defname}) self.pid, stdin, stdout, stderr = GObject.spawn_async(argv, working_directory=chdir, child_setup=self.__setup, standard_input=True, standard_output=True, standard_error=True, flags=GObject.SPAWN_DO_NOT_REAP_CHILD|GObject.SPAWN_SEARCH_PATH) log.debug("SubProcess.__init__: _initChannel...", extra={"task":self.defname}) self.__channelTags = [] self.inChannel = self._initChannel(stdin, None, None, False) readFlags = GObject.IO_IN|GObject.IO_HUP#|GObject.IO_ERR self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb, False) self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb, True) log.debug("SubProcess.__init__: channelsClosed...", extra={"task":self.defname}) self.channelsClosed = False self.channelsClosedLock = threading.Lock() log.debug("SubProcess.__init__: child_watch_add...", extra={"task":self.defname}) GObject.child_watch_add(self.pid, self.__child_watch_callback) log.debug("SubProcess.__init__: subprocExitCode...", extra={"task":self.defname}) self.subprocExitCode = (None, None) self.subprocFinishedEvent = threading.Event() subprocesses.append(self) log.debug("SubProcess.__init__: finished", extra={"task":self.defname})
def _run_synaptic(self, xid, opt, tempf, interaction): deferred = Deferred() if tempf: opt.extend(["--set-selections-file", "%s" % tempf.name]) #FIXME: Take interaction into account opt.extend(["-o", "Synaptic::closeZvt=true"]) if xid: opt.extend(["--parent-window-id", "%s" % (xid)]) cmd = ["/usr/bin/gksu", "--desktop", "/usr/share/applications/update-manager.desktop", "--", "/usr/sbin/synaptic", "--hide-main-window", "--non-interactive"] cmd.extend(opt) flags = GObject.SPAWN_DO_NOT_REAP_CHILD (pid, stdin, stdout, stderr) = GObject.spawn_async(cmd, flags=flags) GObject.child_watch_add(pid, self._on_synaptic_exit, (tempf, deferred)) return deferred
def __init__(self, handle): # fork pygame before we initialize the activity. import os import pygame import sys pygame.init() windowid = pygame.display.get_wm_info()['wmwindow'] self.child_pid = os.fork() if self.child_pid == 0: bp = activity.get_bundle_path() library_path = os.path.join(bp, 'library') pippy_app_path = os.path.join(bp, 'pippy_app.py') sys.path[0:0] = [library_path] g = globals() g['__name__'] = '__main__' execfile(pippy_app_path, g, g) # start pygame sys.exit(0) super(PyGameActivity, self).__init__(handle) from gi.repository import GObject from gi.repository import Gtk self.max_participants = 1 # no sharing toolbox = ToolbarBox() activity_button_toolbar = ActivityToolbarButton(self) toolbox.toolbar.insert(activity_button_toolbar, 0) activity_button_toolbar.show() self.set_toolbar_box(toolbox) toolbox.show() separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) toolbox.toolbar.insert(separator, -1) separator.show() stop_button = StopButton(self) stop_button.props.accelerator = '<Ctrl>q' toolbox.toolbar.insert(stop_button, -1) stop_button.show() toolbox.toolbar.show_all() socket = Gtk.Socket() socket.set_flags(socket.flags() | Gtk.CAN_FOCUS) socket.show() self.set_canvas(socket) socket.add_id(windowid) self.show_all() socket.grab_focus() GObject.child_watch_add(self.child_pid, lambda pid, cond: self.close())
def run(self, cmd): self._cmd = cmd (pid, stdin, stdout, stderr) = GObject.spawn_async( cmd, flags=GObject.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) LOG.debug("running: '%s' as pid: '%s'" % (cmd, pid)) self._child_watch = GObject.child_watch_add( pid, self._helper_finished, data=(stdout, stderr)) self._io_watch = GObject.io_add_watch( stdout, GObject.IO_IN, self._helper_io_ready, (stdout, ))
def run(self, cmd): self._cmd = cmd (pid, stdin, stdout, stderr) = GObject.spawn_async( cmd, flags = GObject.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) LOG.debug("running: '%s' as pid: '%s'" % (cmd, pid)) self._child_watch = GObject.child_watch_add( pid, self._helper_finished, data=(stdout, stderr)) self._io_watch = GObject.io_add_watch( stdout, GObject.IO_IN, self._helper_io_ready, (stdout, ))
def do_spawn_async(event): self.pid, stdin, stdout, stderr = GObject.spawn_async(argv, working_directory=chdir, child_setup=self.__setup, standard_input=True, standard_output=True, standard_error=True, flags=GObject.SPAWN_DO_NOT_REAP_CHILD|GObject.SPAWN_SEARCH_PATH) log.debug("SubProcess.__init__: _initChannel...", extra={"task":self.defname}) self.__channelTags = [] self.inChannel = self._initChannel(stdin, None, None, False) readFlags = GObject.IO_IN|GObject.IO_HUP#|GObject.IO_ERR self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb, False) self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb, True) log.debug("SubProcess.__init__: channelsClosed...", extra={"task":self.defname}) self.channelsClosed = False self.channelsClosedLock = threading.Lock() log.debug("SubProcess.__init__: child_watch_add...", extra={"task":self.defname}) GObject.child_watch_add(self.pid, self.__child_watch_callback, None) if event is not None: event.set()
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 fetch_mail(self): """Shell out to a command to fetch email into a maildir""" logging.info("Calling: %s" % " ".join(self.fetch_cmd)) try: pid, _in, out, err = GObject.spawn_async( self.fetch_cmd, flags=GObject.SPAWN_DO_NOT_REAP_CHILD) except GLib.Error as e: err_s = "spawn failed: %s" % e logging.error(err_s) self.notify(err_s) self.set_timer(self.fetch_interval) # try again in a while return False self.fetch_subprocess_pid = pid self.change_state(self.FETCH_STATE_FETCHING) GObject.child_watch_add(pid, self.fetch_done_callback, None) self.set_timer(self.fetch_timeout) # ensure it doesn't take forever logging.debug("fetch process pid: %d" % pid) return False
def convert(self): src = self.target target = src.replace(self.codec,'.mp3') if os.path.exists(target): os.remove(target) if sys.platform != "linux2": ffmpeg_path = os.path.join(os.path.dirname(os.path.dirname(config.exec_path)),'ffmpeg\\ffmpeg.exe').replace("\\","\\\\") target = target.replace("\\","\\\\") src = src.replace("\\","\\\\") else: ffmpeg_path = "/usr/bin/ffmpeg" self.print_info(_('Extracting audio...')) try: self.gui.throbber.show() #print str(ffmpeg_path), '-i', str(src), '-f', 'mp3', '-ab', '192k', str(target) (pid,t,r,s) = GObject.spawn_async([str(ffmpeg_path), '-i', str(src), '-f', 'mp3', '-ab', '192k', str(target)],flags=GObject.SPAWN_DO_NOT_REAP_CHILD,standard_output = True, standard_error = True) GObject.child_watch_add(pid, self.task_done) except: self.print_info(_('Extraction failed...')) sleep(4) self.print_info('') self.gui.throbber.hide()
def _run_synaptic(self, action, opt, tempf): """Execute synaptic.""" try: apt_pkg.pkgsystem_unlock() except SystemError: pass win = self.window_main.get_window() try: xid = win.get_xid() except AttributeError: xid = 0 cmd = ["/usr/bin/pkexec", "/usr/sbin/synaptic", "--hide-main-window", "--non-interactive", "--parent-window-id", "%s" % xid] cmd.extend(opt) flags = GObject.SPAWN_DO_NOT_REAP_CHILD (pid, stdin, stdout, stderr) = GObject.spawn_async(cmd, flags=flags) # Keep a reference to the data tuple passed to # GObject.child_watch_add to avoid attempts to destroy it without a # thread context: https://bugs.launchpad.net/bugs/724687 self.child_data = (action, tempf) GObject.child_watch_add(pid, self._on_synaptic_exit, self.child_data)
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 | GLib.IO_ERR | GLib.IO_HUP, self._on_lintian_output) GObject.child_watch_add(pid, self._on_lintian_finished)
def do_spawn_async(event): flags = GLib.SPAWN_DO_NOT_REAP_CHILD | GLib.SPAWN_SEARCH_PATH if sys.platform == "win32": flags |= GLib.SPAWN_WIN32_HIDDEN_CONSOLE self.pid, stdin, stdout, stderr = GObject.spawn_async( argv, working_directory=chdir, child_setup=self.__setup, standard_input=True, standard_output=True, standard_error=True, flags=flags) log.debug("SubProcess.__init__: _initChannel...", extra={"task": self.defname}) self.__channelTags = [] self.inChannel = self._initChannel(stdin, None, None, False) readFlags = GObject.IO_IN | GObject.IO_HUP #|GObject.IO_ERR self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb, False) self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb, True) log.debug("SubProcess.__init__: channelsClosed...", extra={"task": self.defname}) self.channelsClosed = False self.channelsClosedLock = threading.Lock() log.debug("SubProcess.__init__: child_watch_add...", extra={"task": self.defname}) # On Python3 pygobject versions before 3.10.0 spawn_async returns pid as 0 # see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=712537 if self.pid != 0: GObject.child_watch_add(self.pid, self.__child_watch_callback, None) if event is not None: event.set()
def attach(self, options=None): if self.mode == 'remote' and self.status() == 0: while not self.isOpen(): time.sleep(1) logging.info('starting vdr-sxfe') self.proc = subprocess.Popen("exec " + self.cmd, shell=True, env=os.environ) GObject.child_watch_add(self.proc.pid, self.on_exit, self.proc) # Add callback on exit if self.proc: self.block = True logging.debug('started vdr-sxfe') if self.proc.poll() is not None: logging.warning("failed to start vdr-sxfe") return False else: logging.debug('vdr-sxfe is still running') self.state = 1 return True elif self.mode == 'local' and self.status() == 0: self.main.dbus2vdr.Plugins.SVDRPCommand('xinelibputput', 'LFRO', 'sxfe') self.state = 1 return True
def execute(self, command): LOG.debug("execute: %s" % command) # run child process self.__process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # unblock pipes fcntl.fcntl(self.__process.stdout, fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(self.__process.stderr, fcntl.F_SETFL, os.O_NONBLOCK) # monitor process and pipes self.__handlers = [ GObject.timeout_add(self.__POLL_INTERVAL, self.__on_stdout), GObject.timeout_add(self.__POLL_INTERVAL, self.__on_stderr), GObject.child_watch_add(self.__process.pid, self.__on_exit) ]
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) = GObject.spawn_async(cmd, flags=GObject.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) LOG.debug("running: '%s' as pid: '%s'" % (cmd, pid)) self._child_watch = GObject.child_watch_add(pid, self._helper_finished, data=(stdout, stderr)) self._io_watch = GObject.io_add_watch(stdout, GObject.IO_IN, self._helper_io_ready, (stdout, ))
def run(self): """ Run the process. """ process_data = gobject.spawn_async( self.command, flags=gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_DO_NOT_REAP_CHILD, standard_output=self.stdout, standard_error=self.stderr, ) self.pid = process_data[0] self.stdout = os.fdopen(process_data[2]) self.stderr = os.fdopen(process_data[3]) print self.stderr self.watch = gobject.child_watch_add(self.pid, self.exited_cb) return self.pid
def execute(self, command): LOG.debug("execute: %s" % command) # run child process self.__process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # unblock pipes fcntl.fcntl(self.__process.stdout, fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(self.__process.stderr, fcntl.F_SETFL, os.O_NONBLOCK) # monitor process and pipes self.__handlers = [ GObject.timeout_add(self.__POLL_INTERVAL, self.__on_stdout), GObject.timeout_add(self.__POLL_INTERVAL, self.__on_stderr), GObject.child_watch_add(self.__process.pid, self.__on_exit) ]
def run(self): """ Run the process. """ """ process_data = gobject.spawn_async(self.command, flags=gobject.SPAWN_SEARCH_PATH|gobject.SPAWN_DO_NOT_REAP_CHILD, standard_output=self.stdout, standard_error=self.stderr ) """ self.process = subprocess.Popen(self.command) self.pid = self.process.pid #self.stdout = os.fdopen(process_data[2]) #self.stderr = os.fdopen(process_data[3]) self.watch = gobject.child_watch_add(self.pid, self.exited_cb) return self.pid
def _create_activity(self): if self._handle.activity_id is None: self._handle.activity_id = create_activity_id() self._shell.NotifyLaunch( self._service_name, self._handle.activity_id, reply_handler=self._no_reply_handler, error_handler=self._notify_launch_error_handler) environ = get_environment(self._bundle) (log_path, log_file) = open_log_file(self._bundle) command = get_command(self._bundle, self._handle.activity_id, self._handle.object_id, self._handle.uri, self._handle.invited) environment_dir = None if os.path.exists('/etc/olpc-security') \ and os.access('/usr/bin/rainbow-run', os.X_OK): environment_dir = tempfile.mkdtemp() command = [ 'sudo', '-E', '--', 'rainbow-run', '-v', '-v', '-a', 'rainbow-sugarize', '-s', '/var/spool/rainbow/2', '-f', '1', '-f', '2', '-c', self._bundle.get_path(), '-u', pwd.getpwuid(os.getuid()).pw_name, '-i', environ['SUGAR_BUNDLE_ID'], '-e', environment_dir, '--', ] + command for key, value in environ.items(): file_path = os.path.join(environment_dir, str(key)) open(file_path, 'w').write(str(value)) log_file.write(' '.join(command) + '\n\n') dev_null = file('/dev/null', 'r') child = subprocess.Popen([str(s) for s in command], env=environ, cwd=str(self._bundle.get_path()), close_fds=True, stdin=dev_null.fileno(), stdout=log_file.fileno(), stderr=log_file.fileno()) GObject.child_watch_add( child.pid, _child_watch_cb, (environment_dir, log_file, self._handle.activity_id))
def arm(self, tasklet): '''See L{WaitCondition.arm}''' self._callback = tasklet.wait_condition_fired if self._id is None: self._id = GObject.child_watch_add(self.pid, self._child_cb)