def build(self): self.create() # change me self._bottom_panel.activate_item(self._panel) # docs = self._window.get_unsaved_documents() # for doc in docs: # if doc.get_uri() != None: # doc.save(0) self._panel.clear() cmdline = "scons -Q debug=1" self.pipe = subprocess.Popen(cmdline.split(" "), stdout=PIPE, stderr=PIPE, cwd=self._directory) gobject.io_add_watch(self.pipe.stdout, gobject.IO_IN | gobject.IO_HUP, self.on_output) gobject.io_add_watch(self.pipe.stderr, gobject.IO_IN | gobject.IO_HUP, self.on_output) self._firstError = True # Wait for the process to complete gobject.child_watch_add(self.pipe.pid, self.on_child_end)
def on_parent_map(self, widget): os.environ['WINE_DESKTOP_PARENT'] = str(self.desktop_parent.window.xid) os.environ['SUGARED_WINE_TOPLEVEL'] = str(self.window.xid) gtk.gdk.flush() os.chdir(self.get_unix_path('c:\\')) width = gtk.gdk.screen_width() height = gtk.gdk.screen_height() cmdline = ('wine', 'explorer', '/desktop=%s,%sx%s' % (self.desktop_name, width, height)) try: args = self.settings['exec'].split(' ') except KeyError: pass else: cmdline += ('start', '/unix') cmdline += (os.path.join(self.bundle_path, args[0]),) cmdline += tuple(args[1:]) self.wine_pid, stdin, stdout, stderr = gobject.spawn_async(cmdline, flags=gobject.SPAWN_SEARCH_PATH|gobject.SPAWN_DO_NOT_REAP_CHILD) gobject.child_watch_add(self.wine_pid, self.on_wine_quit, None) for cmdline in self.to_run: self.start_wine(*cmdline)
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) import gobject 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 openLocalForward(self, localPort, remotePort): """ Open local forwarding. ssh -L is not used because it requires opening a new connection, which can be very slow in some cases. If localPort is 0, a random port above 5900 is selected. Returns localPort. """ import socket import random while localPort == 0: # Get a port above 5900, few VNC clients accept negative VNC # display numbers p = random.randint(6000, 30000) try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', p)) s.close() localPort = p except socket.error: pass p = subprocess.Popen(['socat', 'exec:ssh %s sepiida-connect-port %d' % (self.hostname, remotePort), 'tcp-listen:%d,rcvtimeo=10' % localPort], shell=False, preexec_fn=os.setsid) gobject.child_watch_add(p.pid, lambda pid, condition: None) # avoid defunct process return localPort
def launch(self): ''' Launch the service ''' self.dead = False runner = os.path.join(self.path, 'run') if not os.path.exists(runner): self.lastDied = time() self.dead = True self.parent.log( 'unable to start %s: run does not exist' % self.path) return if not os.access(runner, os.X_OK): self.lastDied = time() self.dead = True self.parent.log( 'unable to start %s: run is not executable' % self.path) return self.parent.log('starting service: %s' % self.path) (self.pid, stdin, stdout, stderr) = gobject.spawn_async( [runner], working_directory=self.path, flags=gobject.SPAWN_DO_NOT_REAP_CHILD) if self.pid <= 0: self.lastDied = time() self.dead = True self.parent.log('failed to start process: %s', self.path) else: gobject.child_watch_add(self.pid, self.died) self.changed('up')
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 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() (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 on_parent_map(self, widget): os.environ['WINE_DESKTOP_PARENT'] = str(self.desktop_parent.window.xid) os.environ['SUGARED_WINE_TOPLEVEL'] = str(self.window.xid) gtk.gdk.flush() os.chdir(self.get_unix_path('c:\\')) width = gtk.gdk.screen_width() height = gtk.gdk.screen_height() cmdline = ('wine', 'explorer', '/desktop=%s,%sx%s' % (self.desktop_name, width, height)) try: args = self.settings['exec'].split(' ') except KeyError: pass else: cmdline += ('start', '/unix') cmdline += (os.path.join(self.bundle_path, args[0]), ) cmdline += tuple(args[1:]) self.wine_pid, stdin, stdout, stderr = gobject.spawn_async( cmdline, flags=gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_DO_NOT_REAP_CHILD) gobject.child_watch_add(self.wine_pid, self.on_wine_quit, None) for cmdline in self.to_run: self.start_wine(*cmdline)
def startProcess(self, cmdArgs, description = "", killOnTermination=True, exitHandler=None, exitHandlerArgs=(), **kwargs): process = subprocess.Popen(cmdArgs, stdin=open(os.devnull), startupinfo=plugins.getProcessStartUpInfo(), **kwargs) pidOrHandle = self.getProcessIdentifier(process) self.exitHandlers[int(pidOrHandle)] = (exitHandler, exitHandlerArgs) if killOnTermination: self.processesForKill[int(pidOrHandle)] = (process, description) gobject.child_watch_add(pidOrHandle, self.processExited)
def handleVnc(self, server, port, protocol, cbStatus, viewonly=False, password=''): """ Handle setting up VNC connection to port on server. cbStatus is called back with status messages, and finally an empty string when the VNC client is started. """ cbStatus(_('Opening port forwarding...')) localPort = server.openLocalForward(0, port) vncArgv = ['xtightvncviewer', 'localhost::%d' % localPort, '-encodings', 'tight zrle copyrect'] rdpArgv = ['rdesktop', 'localhost:%d' % localPort] if viewonly: vncArgv.append('-viewonly') if password: vncArgv.append('-autopass') # pass password on stdin if protocol == 'vnc': p = subprocess.Popen(vncArgv, shell=False, stdin=subprocess.PIPE) if password: p.stdin.write(password) p.stdin.close() elif protocol == 'rdp': p = subprocess.Popen(rdpArgv, shell=False, stdin=subprocess.PIPE) else: cbStatus(_('unknown protocol %s' % protocol)) return gobject.child_watch_add(p.pid, lambda pid, condition: None) # avoid defunct process cbStatus(_('%s client started.') % protocol.upper()) cbStatus('')
def download(self, grabber_command=None): if not grabber_command: grabber_command = self.config.grabber_command grabber = subprocess.Popen(grabber_command.split()) self.emit("downloading") gobject.child_watch_add(grabber.pid, self.__process_completed, ("downloading",), priority=gobject.PRIORITY_HIGH) if self.config.debug: print('Downloading with grabber command "%s".' % grabber_command)
def sort(self, file=None): if not file: file = self.path tv_sort = subprocess.Popen(["tv_sort", file, "--output", file]) self.emit("sorting") gobject.child_watch_add(tv_sort.pid, self.__process_completed, ("sorting",), priority=gobject.PRIORITY_HIGH) if self.config.debug: print('Sorting "%s".' % file)
def cmd_vivicate(self, klass, name, *args, **kwargs): id = (klass, name) child = self.get_child(id) if child is None: child = ChildProxy(klass, id, *args, **kwargs) self.children.append(child) gobject.child_watch_add(child.pid, self._on_child_exit) return True
def attach(self,frontend=True): logging.info('starting xbmc') try: self.proc = subprocess.Popen(self.cmd,env=self.environ) 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 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 _start_forwarding(self): args = ['ssh', self.target, '-o', 'PasswordAuthentication no', '-N', '-R', '21693:localhost:21693'] if self.keyfile: args[2:2] = ['-i', self.keyfile] flags = gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_DO_NOT_REAP_CHILD self.ssh_pid, stdin_fd, stdout_fd, stderr_fd = \ gobject.spawn_async(args, flags=flags) gobject.child_watch_add(self.ssh_pid, self._restart_forwarding)
def Run(self): self.pid, stdin, self.stdout, self.stderr = gobject.spawn_async( self.argv, flags=gobject.SPAWN_DO_NOT_REAP_CHILD, # make sure we can handle it's exit standard_input=False, standard_output=True, standard_error=True) gobject.child_watch_add(self.pid, self.__HandleExit)
def _check_agent_is_loaded(self): self.label.set_text("checking agent") pid, stdin, stdout, stderr = gobject.spawn_async( ["ssh-add", "-L"], flags=gobject.SPAWN_DO_NOT_REAP_CHILD| gobject.SPAWN_STDOUT_TO_DEV_NULL| gobject.SPAWN_SEARCH_PATH) pid.close() gobject.child_watch_add(pid, self._check_agent_is_loaded_cb)
def Run(self): self.pid, stdin, self.stdout, self.stderr = gobject.spawn_async( self.argv, flags = gobject.SPAWN_DO_NOT_REAP_CHILD, # make sure we can handle it's exit standard_input=False, standard_output=True, standard_error=True ) gobject.child_watch_add(self.pid, self.__HandleExit)
def on_flushed_child_exit(pid, fd_forwarders, callback): reason_to_run = plash.mainloop.ReasonToRun() def exit_callback(pid_unused, status): reason_to_run.dispose() def on_flush(): callback(status) flush_multiple_forwarders(fd_forwarders, on_flush) gobject.child_watch_add(pid, exit_callback)
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 install_pkgs(self): try: (pid, sin, sout, serr) = gobject.spawn_async( ["install-langs", tmpdir], flags=gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_DO_NOT_REAP_CHILD) gobject.child_watch_add(pid, self.install_pkgs_done) if self.window.window: self.window.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) except gobject.GError: self.install = False install_pkgs_done(self, None, None)
def run_vdr(self): logging.info(u"starting PIP vdr") self.proc = subprocess.Popen(self.cmd, shell=True) # Spawn process gobject.child_watch_add(self.proc.pid,self.on_exit,self.proc) # Add callback on exit while not self.shddbus: try: self.shddbus = self.main_instance.systembus.get_object("de.tvdr.vdr1","/Plugins/softhddevice") self.remote = self.main_instance.systembus.get_object("de.tvdr.vdr1","/Remote") logging.debug('dbus2vdr of pip vdr ready') except: logging.debug(u"dbus2vdr not jet ready") time.sleep(0.5)
def start(self): self.proc = subprocess.Popen( self.args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) self._out = gobject.io_add_watch(self.proc.stdout, gobject.IO_IN, self.on_buff_read, "stdout-data") self._err = gobject.io_add_watch(self.proc.stderr, gobject.IO_IN, self.on_buff_read, "stderr-data") gobject.child_watch_add(self.proc.pid, self.on_finished) self.emit("started", self.proc.pid)
def _NMConfig(self, *args): self.intf.icw.window.set_sensitive(False) cmd = ["/usr/bin/nm-connection-editor"] out = open("/dev/tty5", "w") try: proc = subprocess.Popen(cmd, stdout=out, stderr=out) except Exception as e: self.intf.icw.window.set_sensitive(True) import logging log = logging.getLogger("anaconda") log.error("Could not start nm-connection-editor: %s" % e) else: gobject.child_watch_add(proc.pid, self._NMExited, data=None, priority=gobject.PRIORITY_DEFAULT)
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) try: pid, stdin, stdout, stderr = \ gobject.spawn_async(argv, flags=flags, **opts) 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 start(self): try: proc = subprocess.Popen(*self.args, **self.kwargs) self.__pid = proc.pid self.__id = gobject.child_watch_add(self.pid, self.__on_finish) except Exception, e: print "Error:", e
def _execute(self, options): """ Launch the monitored process """ if options is None: cmdline = self._cmdline else: cmdline = [self._cmdline[0]] + options.split() result = gobject.spawn_async( cmdline, envp="", working_directory=os.environ.get("PWD", "/"), flags=gobject.SPAWN_DO_NOT_REAP_CHILD, # needed for child watch user_data=None, standard_input=False, standard_output=True, standard_error=True) if result[0] < 0: raise OSError("foo") self.pid, self.stdin, self.stdout, self.stderr = result self._childwatch = gobject.child_watch_add(self.pid, self._exitFromChild, priority=100) self._stdoutwatch = gobject.io_add_watch(self.stdout, gobject.IO_IN, self._outputFromChild) self._stderrwatch = gobject.io_add_watch(self.stderr, gobject.IO_IN, self._errorFromChild)
def start (self): try: proc = subprocess.Popen (*self.args, **self.kwargs) self.__pid = proc.pid self.__id = gobject.child_watch_add (self.pid, self.__on_finish) except Exception, e: print "Error:", e
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) try: pid, stdin, stdout, stderr = \ gobject.spawn_async(argv, flags=flags, **opts) 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 __init__(self, path, args=[], warnwords=[], env=None): 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", 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 + "\n", self.defname) argv = [str(u) for u in [self.path] + self.args] self.pid, stdin, stdout, stderr = gobject.spawn_async( argv, child_setup=self.__setup, standard_input=True, standard_output=True, standard_error=True, flags=gobject.SPAWN_DO_NOT_REAP_CHILD | gobject.SPAWN_SEARCH_PATH) 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) self.channelsClosed = False self.channelsClosedLock = threading.Lock() gobject.child_watch_add(self.pid, self.__child_watch_callback) self.subprocExitCode = (None, None) self.subprocFinishedEvent = threading.Event() self.subprocFinishedEvent.clear() subprocesses.append(self) pool.start(self._wait4exit)
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 start_app(self,cmd,detachf=True, exitOnPID=True, environment=os.environ): logging.info('starting %s',cmd) if self.settings.frontend_active == 1 and detachf == True: logging.info('detaching frontend') self.dbusService.deta() self.wnckC.windows['frontend'] = None self.settings.reattach = 1 else: self.settings.reattach = 0 if cmd != ' ' and cmd != None and len(cmd)!=0: os.chdir(os.environ['HOME']) logging.info('starting cmd: %s',cmd) try: self.settings.external_proc[cmd] = subprocess.Popen(cmd, env=environment, shell=True) except: logging.exception('APP-Start failed: %s',cmd) if exitOnPID: gobject.child_watch_add(self.settings.external_proc[cmd].pid,self.on_exit,cmd) # Add callback on exit
def spawn(self, args=None, callback=None, data=None, cwd=None): '''Run application in the background and return immediatly. The optional callback can be used to trigger when the application exits. The signature is: callback(status) where 'status' is the exit status of the process. The application object provides a constant 'STATUS_OK' which can be used to test if the application was successful or not. ''' # TODO: can we build this based on os.spawn ? - seems this method fails on win32 cwd, argv = self._checkargs(cwd, args) opts = {} if cwd: opts['cwd'] = unicode(cwd).encode('utf-8') flags = gobject.SPAWN_SEARCH_PATH if callback: flags |= gobject.SPAWN_DO_NOT_REAP_CHILD # without this flag child is reaped autmatically -> no zombies logger.info('Spawning: %s (cwd: %s)', argv, cwd) try: pid, stdin, stdout, stderr = \ gobject.spawn_async(argv, flags=flags, **opts) except gobject.GError: logger.exception('Failed running: %s', argv) name = self.name #~ ErrorDialog(None, _('Could not run application: %s') % name).run() #~ # T: error when application failed to start return None else: logger.debug('Process started with PID: %i', pid) if callback: # child watch does implicite 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 runNMCE(anaconda=None, blocking=True): if not blocking and anaconda: anaconda.intf.icw.window.set_sensitive(False) cmd = ["/usr/bin/nm-connection-editor"] out = open("/dev/tty5", "w") try: proc = subprocess.Popen(cmd, stdout=out, stderr=out) except Exception as e: if not blocking and anaconda: anaconda.intf.icw.window.set_sensitive(True) import logging log = logging.getLogger("anaconda") log.error("Could not start nm-connection-editor: %s" % e) return None else: if blocking: proc.wait() else: gobject.child_watch_add(proc.pid, NMCEExited, data=anaconda, priority=gobject.PRIORITY_DEFAULT)
def run(self): """ Run the process. """ process_data = gobject.spawn_async(self.command, flags=gobject.SPAWN_SEARCH_PATH|gobject.SPAWN_DO_NOT_REAP_CHILD ) self.pid = process_data[0] self.watch = gobject.child_watch_add(self.pid, self.exited_cb) return self.pid
def __init__(self, path, args=[], warnwords=[], env=None): 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", 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+"\n", self.defname) argv = [str(u) for u in [self.path]+self.args] self.pid, stdin, stdout, stderr = gobject.spawn_async(argv, child_setup=self.__setup, standard_input=True, standard_output=True, standard_error=True, flags=gobject.SPAWN_DO_NOT_REAP_CHILD|gobject.SPAWN_SEARCH_PATH) 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) self.channelsClosed = False self.channelsClosedLock = threading.Lock() gobject.child_watch_add(self.pid, self.__child_watch_callback) self.subprocExitCode = (None, None) self.subprocFinishedEvent = threading.Event() self.subprocFinishedEvent.clear() subprocesses.append(self) pool.start(self._wait4exit)
def execute(self, command): self.__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 Start(self): """Start program. """ logging.info("Starting program, executable=%r, args=%r", self.__executable, self.__args) # TODO: Make gobject.SPAWN_SEARCH_PATH controllable by caller? flags = gobject.SPAWN_DO_NOT_REAP_CHILD | gobject.SPAWN_SEARCH_PATH if self.__executable: args = self.__FormatArgs([self.__executable] + self.__args) flags |= gobject.SPAWN_FILE_AND_ARGV_ZERO else: args = self.__FormatArgs(self.__args) # gobject.spawn_async doesn't take None for default values, hence we can # only fill these parameters if they need to be set. kwargs = {} if self.__env is not None: kwargs["envp"] = self.__FormatEnvironment(self.__env) if self.__cwd is not None: kwargs["working_directory"] = self.__cwd (pid, stdin_fd, stdout_fd, stderr_fd) = \ gobject.spawn_async(args, flags=flags, child_setup=self.__ChildSetup, standard_input=True, standard_output=True, standard_error=True, **kwargs) logging.info("Child %s[%d] started", self.__progname, pid) self.__pid = pid self.stdin.Attach(stdin_fd) self.stdout.Attach(stdout_fd) self.stderr.Attach(stderr_fd) self.__child_watch_handle = \ gobject.child_watch_add(self.__pid, self.__HandleExit) return self.pid
def start(self): progname='tuxpaint' tuxpaint_dir = None flags = gobject.SPAWN_DO_NOT_REAP_CHILD | gobject.SPAWN_SEARCH_PATH print platform.platform(), platform.platform().split('-')[0] if (platform.platform().split('-')[0] == 'Windows'): progname = 'tuxpaint.exe' try: import _winreg tuxpaint_key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, "Software\\TuxPaint" ) tuxpaint_dir, type = _winreg.QueryValueEx(tuxpaint_key, "Install_Dir") flags = gobject.SPAWN_DO_NOT_REAP_CHILD # escape mandatory in Win pygtk2.6 tuxpaint_dir = '"' + tuxpaint_dir + '"' except: pass self.window = self.gcomprisBoard.canvas.get_toplevel() Prop = gcompris.get_properties() #get default values self.config_dict = self.init_config() #replace configured values self.config_dict.update(gcompris.get_board_conf()) self.rootitem = goocanvas.Group(parent = self.gcomprisBoard.canvas.get_root_item()) options = [progname] if (Prop.fullscreen and eval(self.config_dict['fullscreen'])): options.append('--fullscreen') if eval(self.config_dict['disable_shape_rotation']): options.append('--simpleshapes') if eval(self.config_dict['uppercase_text']): options.append('--uppercase') if eval(self.config_dict['disable_stamps']): options.append('--nostamps') if eval(self.config_dict['disable_stamps_control']): options.append('--nostampcontrols') gcompris.sound.close() global pid try: # bug in working_directory=None ? if (tuxpaint_dir): pid, stdin, stdout, stderr = gobject.spawn_async( argv=options, flags=flags, working_directory=tuxpaint_dir) else: pid, stdin, stdout, stderr = gobject.spawn_async( argv=options, flags=flags) except: gcompris.utils.dialog(_("Cannot find Tuxpaint.\nInstall it to use this activity !"),stop_board) return gobject.child_watch_add(pid, child_callback, data=self, priority=gobject.PRIORITY_HIGH) gcompris.bar_set(gcompris.BAR_CONFIG) gcompris.bar_hide(1) gcompris.set_default_background(self.gcomprisBoard.canvas.get_root_item()) textItem = goocanvas.Text( parent = self.rootitem, text = _("Waiting for Tuxpaint to finish"), x = gcompris.BOARD_WIDTH/2, y = 185, fill_color_rgba = 0x000000ffL, anchor = gtk.ANCHOR_CENTER, font = gcompris.skin.get_font("gcompris/board/title bold"), )
class Capture(gobject.GObject): CAPTURE_STDOUT = 0x01 CAPTURE_STDERR = 0x02 CAPTURE_BOTH = 0x03 CAPTURE_NEEDS_SHELL = 0x04 WRITE_BUFFER_SIZE = 0x4000 __gsignals__ = { 'stdout-line' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)), 'stderr-line' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)), 'begin-execute': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, tuple()), 'end-execute' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_INT,)) } def __init__(self, command, cwd = None, env = {}): gobject.GObject.__init__(self) self.pipe = None self.env = env self.cwd = cwd self.flags = self.CAPTURE_BOTH | self.CAPTURE_NEEDS_SHELL self.command = command self.input_text = None def set_env(self, **values): self.env.update(**values) def set_command(self, command): self.command = command def set_flags(self, flags): self.flags = flags def set_input(self, text): self.input_text = text def set_cwd(self, cwd): self.cwd = cwd def execute(self): if self.command is None: return # Initialize pipe popen_args = { 'cwd' : self.cwd, 'shell': self.flags & self.CAPTURE_NEEDS_SHELL, 'env' : self.env } if self.input_text is not None: popen_args['stdin'] = subprocess.PIPE if self.flags & self.CAPTURE_STDOUT: popen_args['stdout'] = subprocess.PIPE if self.flags & self.CAPTURE_STDERR: popen_args['stderr'] = subprocess.PIPE self.tried_killing = False self.idle_write_id = 0 self.read_buffer = '' try: self.pipe = subprocess.Popen(self.command, **popen_args) except OSError, e: self.pipe = None self.emit('stderr-line', _('Could not execute command: %s') % (e, )) return # Signal self.emit('begin-execute') if self.flags & self.CAPTURE_STDOUT: # Set non blocking 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) if self.flags & self.CAPTURE_STDERR: # Set non blocking flags = fcntl.fcntl(self.pipe.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK fcntl.fcntl(self.pipe.stderr.fileno(), fcntl.F_SETFL, flags) gobject.io_add_watch(self.pipe.stderr, gobject.IO_IN | gobject.IO_HUP, self.on_output) # IO if self.input_text is not None: # Write async, in chunks of something self.write_buffer = str(self.input_text) if self.idle_write_chunk(): self.idle_write_id = gobject.idle_add(self.idle_write_chunk) # Wait for the process to complete gobject.child_watch_add(self.pipe.pid, self.on_child_end)
def add_child_watch(self, pid, func, *args): '''Add a new child process watcher for exitng PID. Wrap gobject call to child_watch_add''' gobject.child_watch_add(pid, func, *args)
def perform_action(self): cmd = '' if self.action == ACTION_RECV: self.wiz.set_page_title(self.progress_page, _('Receiving...')) port = self.xml.get_widget('listen_port').get_text() dest_dir = self.xml.get_widget('recv_dir').get_filename() self.config.set('history', 'listen_port', port) self.config.set('history', 'recv_dir', dest_dir) cmd = "nc -l -v --close -p %s | tar -xvz -C '%s'" % (port, dest_dir) else: # ACTION_SEND self.wiz.set_page_title(self.progress_page, _('Sending...')) host = self.xml.get_widget('dest_host').get_text() port = self.xml.get_widget('dest_port').get_text() self.config.set('history', 'dest_host', host) self.config.set('history', 'dest_port', port) files = ' ' dirs = [] for it in self.send_list: # special char like single quote should be escaped files += ("'%s' " % it[1].replace("'", "'\\''")) # FIXME: how to escape dir names correctly for transformation pattern? dir = os.path.dirname(it[1]) if not dir in dirs: dirs.append(dir) transform = '--show-transformed-names ' # sort the dirs to put the longer ones before shorter ones dirs.sort(lambda a, b: len(b) - len(a)) # use --transform to strip all prefix of the added files for dir in dirs: transform += ("--transform='s,^%s/,,' " % dir) # striping dir paths of those files with --transform cmd = "tar %s -cvzP %s| nc -w30 -v --close '%s' %s" % ( transform, files, host, port) self.progress.insert( self.progress.get_end_iter(), '%s %s\n\n%s\n\n' % (_('Execute command:'), _('Processing...'), cmd)) # print cmd (self.pid, self.stdi, self.stdo, self.stde) = gobject.spawn_async( ['sh', '-c', ('exec %s' % cmd)], flags=gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_DO_NOT_REAP_CHILD, standard_input=True, standard_output=True, standard_error=True) gobject.child_watch_add(self.pid, self.on_process_exit) gobject.io_add_watch(self.stdo, gobject.IO_IN | gobject.IO_HUP | gobject.IO_ERR, self.on_stdout) gobject.io_add_watch(self.stde, gobject.IO_IN | gobject.IO_HUP | gobject.IO_ERR, self.on_stderr) # enable the Cancel button with very dirty hacks def find_cancel_btn(btn, _self): if btn and gobject.type_is_a( btn, gtk.Button) and btn.get_label() == gtk.STOCK_CANCEL: _self.cancel_btn = btn def find_hbox(w, _self): if w and gobject.type_is_a(w, gtk.HBox): w.forall(find_cancel_btn, _self) self.wiz.forall(find_hbox, self) if self.cancel_btn: self.cancel_btn.set_sensitive(True)