def send_to(self, action, shell): entries = shell.props.selected_source.get_entry_view( ).get_selected_entries() cmdline = ['nautilus-sendto' ] + [entry.get_playback_uri() for entry in entries] glib.spawn_async(argv=cmdline, flags=glib.SPAWN_SEARCH_PATH)
def send_to(self, action, shell): page = shell.props.selected_page if not hasattr(page, "get_entry_view"): return entries = page.get_entry_view().get_selected_entries() cmdline = ['nautilus-sendto'] + [entry.get_playback_uri() for entry in entries] glib.spawn_async(argv=cmdline, flags=glib.SPAWN_SEARCH_PATH)
def send_to(self, action, shell): page = shell.props.selected_page if not hasattr(page, "get_entry_view"): return entries = page.get_entry_view().get_selected_entries() cmdline = ['nautilus-sendto' ] + [entry.get_playback_uri() for entry in entries] glib.spawn_async(argv=cmdline, flags=glib.SPAWN_SEARCH_PATH)
def spawn_async(args): try: glib.spawn_async(args, flags=glib.SPAWN_SEARCH_PATH) return True except Exception, e: message_dialog = gtk.MessageDialog(flags=gtk.DIALOG_MODAL, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE) message_dialog.set_markup("<span size='larger' weight='bold'>%s</span>\n\n '%s'" % ( _("Cannot execute program:"), cgi.escape(' '.join(args)))) resp = message_dialog.run() if resp == gtk.RESPONSE_CLOSE: message_dialog.destroy() return False
def start_vim_hidden(self, extra_args=[], is_preload=False): """ Open a new hidden Vim window Return (window, preload_id) """ window = gtk.Window() window.set_default_size(*WINDOW_SIZE_NOTE) server_id = self.generate_vim_server_id() socket = gtk.Socket() window.realize() window.add(socket) socket.show() socket.connect("plug-added", self.on_socket_plug_added, server_id, window, is_preload) argv = [VIM, '-g', '-f', '--socketid', '%s' % socket.get_id()] argv.extend(['--servername', server_id]) argv.extend(VIM_EXTRA_FLAGS) argv.extend(['-c', 'so %s' % self.write_vimrc_file()]) argv.extend(extra_args) log("Spawning", argv) pid, sin, sout, serr = \ glib.spawn_async(argv, child_setup=self.on_spawn_child_setup, flags=glib.SPAWN_SEARCH_PATH|glib.SPAWN_DO_NOT_REAP_CHILD) glib.child_watch_add(pid, self.on_vim_exit, window) return window
def extern_load_uri(uri): """ extern_load_uri(uri) -> First attempts to load the uri with gtk.show_uri. If that fails it trys xdg-open, gnome-open, and exo-open. """ try: # Try gtk.show_uri. ret = gtk.show_uri(gtk.gdk.screen_get_default(), uri, int(glib.get_current_time())) if ret: return True except Exception as err: print("Error (%s) while loading uri: %s" % (err, uri)) app_list = ['xdg-open', 'gnome-open', 'exo-open'] for app in app_list: try: proc_tup = glib.spawn_async([app, uri], flags=glib.SPAWN_SEARCH_PATH) except Exception as err: print("Error (%s) while loading uri (%s) with app (%s)" % \ (err, uri, app)) # Go to the next app if there was an error. continue # If it gets here than it spawned without error. return True return False
def __init__(self, argv, finish_callback, timeout_s, stdin=None): self.stdout = [] self.stderr = [] self.stdin = [] self.timeout = False self.killed = False self.finished = False self.finish_callback = finish_callback argv = _argv_to_locale(argv) pretty.print_debug(__name__, "AsyncCommand:", argv) flags = (glib.SPAWN_SEARCH_PATH | glib.SPAWN_DO_NOT_REAP_CHILD) pid, stdin_fd, stdout_fd, stderr_fd = \ glib.spawn_async(argv, standard_output=True, standard_input=True, standard_error=True, flags=flags) 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 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) kwargs = {} if display: # environment is passed as a sequence of strings envd = os.environ.copy() envd['DISPLAY'] = display kwargs['envp'] = ['='.join((k, v)) for k, v in envd.items()] try: pid, stdin_fd, stdout_fd, stderr_fd = \ glib.spawn_async(argv, flags=flags, child_setup=_try_register_pr_pdeathsig, **kwargs) except glib.GError as exc: raise utils.SpawnError(unicode(exc)) if pid: glib.child_watch_add(pid, _on_child_exit, (argv, respawn)) return pid
def __init__(self, argv, finish_callback, timeout_s, stdin=None, env=""): self.stdout = [] self.stderr = [] self.stdin = [] self.timeout = False self.killed = False self.finished = False self.finish_callback = finish_callback argv = _argv_to_locale(argv) pretty.print_debug(__name__, "AsyncCommand:", argv) # get default environment var if not given env = env or ['='.join(kv) for kv in os.environ.iteritems()] flags = (glib.SPAWN_SEARCH_PATH | glib.SPAWN_DO_NOT_REAP_CHILD) pid, stdin_fd, stdout_fd, stderr_fd = \ glib.spawn_async(argv, standard_output=True, standard_input=True, standard_error=True, flags=flags, envp=env) 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 process_archive(self, cfile, fi): from subprocess import Popen, PIPE ct = Popen(["/usr/bin/env", "file", "-b", "--mime-type", cfile.get_path()], stdout=PIPE).communicate()[0].strip() if ct == 'application/x-rar': cmd = ['unrar', 'x', '-y'] elif ct == 'application/zip': cmd = ['unzip', '-o'] elif ct == 'application/x-7z-compressed': cmd = ['7z', 'x', '-y'] else: print ct return False folder = gio.file_parse_name('/tmp/fmd-archive-cache/' + fi.get_display_name()) if not folder.query_exists(): folder.make_directory_with_parents() cmd.append(self.current_folder.get_child(fi.get_name()).get_path()) pid, _, _, _ = glib.spawn_async(cmd, working_directory=folder.get_path(), flags=glib.SPAWN_SEARCH_PATH) self.set_uri(folder.get_uri()) return True
def spawn_app(app_info, argv, filelist, workdir=None, startup_notify=True, timestamp=None, launch_cb=None, screen=None): """ Spawn app. @argv: argument list including files @workdir: where to set workdir if not cwd @app_info: Used for startup notification, if @startup_notify is True @filelist: Used for startup notification @startup_notify: Use startup notification @timestamp: Event timestamp @launch_cb: Called if successful with (argv, pid, notify_id, filelist, timestamp) @screen: GdkScreen on which to put the application return pid if successful raise SpawnError on error """ notify_id = None if startup_notify: ctx = gtk.gdk.AppLaunchContext() ctx.set_timestamp(timestamp or gtk.get_current_event_time()) if screen: ctx.set_screen(screen) # This not only returns the string ID but # it actually starts the startup notification! notify_id = ctx.get_startup_notify_id(app_info, filelist) child_env_add = {STARTUP_ENV: notify_id} else: child_env_add = {} if screen: child_env_add["DISPLAY"] = screen.make_display_name() if not workdir or not os.path.exists(workdir): workdir = "." argv = list(locale_encode_argv(argv)) try: (pid, _ig1, _ig2, _ig3) = glib.spawn_async(argv, working_directory=workdir, flags=glib.SPAWN_SEARCH_PATH, child_setup=child_setup, user_data=child_env_add) debug_log("Launched", argv, notify_id, "pid:", pid) except glib.GError as exc: error_log("Error Launching ", argv, unicode(exc)) if notify_id: gtk.gdk.notify_startup_complete_with_id(notify_id) raise SpawnError(unicode(exc)) if launch_cb: launch_cb(argv, pid, notify_id, filelist, timestamp) return pid
def spawn_async(args): try: glib.spawn_async(args, flags=glib.SPAWN_SEARCH_PATH) return True except Exception, e: message_dialog = gtk.MessageDialog(flags=gtk.DIALOG_MODAL, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE) message_dialog.set_markup( "<span size='larger' weight='bold'>%s</span>\n\n '%s'" % (_("Cannot execute program:"), cgi.escape(' '.join(args)))) resp = message_dialog.run() if resp == gtk.RESPONSE_CLOSE: message_dialog.destroy() return False
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_app(app_info, argv, filelist, workdir=None, startup_notify=True, timestamp=None, launch_cb=None, screen=None): """ Spawn app. @argv: argument list including files @workdir: where to set workdir if not cwd @app_info: Used for startup notification, if @startup_notify is True @filelist: Used for startup notification @startup_notify: Use startup notification @timestamp: Event timestamp @launch_cb: Called if successful with (argv, pid, notify_id, filelist, timestamp) @screen: GdkScreen on which to put the application return pid if successful raise SpawnError on error """ notify_id = None if startup_notify: ctx = gtk.gdk.AppLaunchContext() ctx.set_timestamp(timestamp or gtk.get_current_event_time()) if screen: ctx.set_screen(screen) # This not only returns the string ID but # it actually starts the startup notification! notify_id = ctx.get_startup_notify_id(app_info, filelist) child_env_add = {STARTUP_ENV: notify_id} else: child_env_add = {} if screen: child_env_add["DISPLAY"] = screen.make_display_name() if not workdir or not os.path.exists(workdir): workdir = "." argv = list(locale_encode_argv(argv)) try: (pid, _ig1, _ig2, _ig3) = glib.spawn_async( argv, working_directory=workdir, flags=glib.SPAWN_SEARCH_PATH, child_setup=child_setup, user_data=child_env_add, ) debug_log("Launched", argv, notify_id, "pid:", pid) except glib.GError as exc: error_log("Error Launching ", argv, unicode(exc)) if notify_id: gtk.gdk.notify_startup_complete_with_id(notify_id) raise SpawnError(unicode(exc)) if launch_cb: launch_cb(argv, pid, notify_id, filelist, timestamp) return pid
def __start_setup(self): if self.__setup_pid != None: try: # if setup dialog is running, bring the dialog to front by SIGUSR1 os.kill(self.__setup_pid, signal.SIGUSR1) return except OSError: # seems the setup dialog is not running anymore self.__setup_pid.close() self.__setup_pid = None pid = glib.spawn_async(argv=[self.__setup_cmd, "ibus-setup"], flags=glib.SPAWN_DO_NOT_REAP_CHILD)[0] self.__setup_pid = pid glib.child_watch_add(self.__setup_pid, self.__child_watch_cb)
def run(self): """Start the programm and retrieve the output.""" flags = glib.SPAWN_SEARCH_PATH | glib.SPAWN_DO_NOT_REAP_CHILD log("spawn > start > " + repr(self.exe)) try: data = glib.spawn_async(self.exe, [], self.pwd, flags, None, None, False, True, True) self.pid = data[0] glib.child_watch_add(self.pid, self.callback_end) except: return False out = os.fdopen(data[2], 'r') err = os.fdopen(data[3], 'r') self.wid[0] = glib.io_add_watch(data[2], glib.IO_IN|glib.IO_HUP, self.read_callback, out, 1) self.wid[1] = glib.io_add_watch(data[3], glib.IO_IN|glib.IO_HUP, self.read_callback, err, 2) self.isrunning = True return True
def new_vimdow_preloaded(self, name, filepath): if not self.preload_ids: raise RuntimeError("No Preloaded instances found!") preload_id, window = self.preload_ids.popitem() window.set_title(name) self.open_files[filepath] = window ## Note: Filename requires escaping (but our defaults are safe ones) preload_argv = [VIM, '-g', '-f', '--servername', preload_id, '--remote-send', '<ESC>:e %s<CR><CR>' % filepath] log("Using preloaded", preload_argv) ## watch this process pid, sin, sout, serr = glib.spawn_async(preload_argv, flags=glib.SPAWN_SEARCH_PATH|glib.SPAWN_DO_NOT_REAP_CHILD) glib.child_watch_add(pid, self.on_vim_remote_exit, preload_argv) self.position_window(window, filepath) window.present() self.emit("note-opened", filepath, window)
def on_click(self, foo): glib.spawn_async([update_program])
def checksources(self, foo): glib.spawn_async(["/usr/bin/gksu", "/usr/bin/software-properties-gtk"])
def open_folder(_, entry=entry): path = entry.base_path if isinstance(entry.base_path, unicode): path = path.encode(sys.getfilesystemencoding()) glib.spawn_async([b"xdg-open", path], flags=glib.SPAWN_SEARCH_PATH)
def exec_app(self, command, argv=''): print 'Launching %s!' % command real_argv = [command] + shlex.split(argv) print real_argv glib.spawn_async(real_argv, flags=glib.SPAWN_SEARCH_PATH | glib.SPAWN_STDOUT_TO_DEV_NULL | glib.SPAWN_STDERR_TO_DEV_NULL)
def InstallPackageName(self, xid, timestamp, name): glib.spawn_async([self.gpk_install_package_name, name])
def spectrogram(self, filename, wavfile, framerate, msmode=False, hzmode=False, minX=None,maxX=None,minY=None,maxY=None): increment = 128 nwindow = 256 window = flattop(nwindow) nfft = nwindow # Convert wavfile into array wavfile_array = [] for i in wavfile: wavfile_array.append(i) numPoints = len(wavfile) spec = [] for i in range(0,len(wavfile_array)-nwindow,increment): buf = wavfile_array[i:i+nwindow] N = nwindow X = abs(fft.fft(window*buf, nfft)) f = linspace(0,framerate,N+1)[:N] Nout = N/2 + 1 spec.append(X[Nout:]) timescale = 1 if msmode: timescale = 1000 freqscale = 0.001 if hzmode: freqscale = 1 scale = 1 spec = transposed(spec) FILE = open(filename+'_SA_.z', 'w') FILE.write('! nx '+str(len(spec[0]))+' ny '+str(len(spec)/scale)+' xmin 0 xmax '+str(timescale*len(wavfile_array)/float(framerate))+' ymin 0 ymax '+str(freqscale*framerate/2.0)+"\n") maxval = -100 for y in range(0,len(spec),scale): for x in range(0,len(spec[y]),1): if spec[y][x] > maxval: maxval = spec[y][x] maxval = float(maxval) for y in range(0,len(spec),scale): for x in range(0,len(spec[y]),1): FILE.write(str(1-spec[len(spec)-y-1][x]/maxval)+" ") FILE.write("\n") FILE.close() if minX == None: minX = 0 if maxX == None: maxX = float(len(wavfile))/framerate if minY == None: minY = 0 if maxY == None: maxY = float(framerate)/2 s = ['size '+str(self.width)+' '+str(self.height)] s.append('include "color.gle"') s.append('set font psh') s.append('set hei 0.4') s.append('begin graph') s.append('nobox') s.append('x2axis off') s.append('y2axis off') if msmode: s.append('xtitle "Time (ms)"') else: s.append('xtitle "Time (s)"') if hzmode: s.append('ytitle "Frequency (Hz)"') else: s.append('ytitle "Frequency (kHz)"') s.append('xticks length -0.1') s.append('yticks length -0.1') s.append('title ""') s.append('xaxis min '+str(minX)+' max '+str(maxX)) s.append('yaxis min '+str(minY*freqscale)+' max '+str(maxY*freqscale)) s.append('colormap "'+filename.rsplit('/')[-1]+'_SA_.z" 300 200 color') s.append('end graph') FILE = open(filename+'_SA_.gle', 'w') FILE.writelines('\n'.join(s)) FILE.close() glecall = ['/usr/bin/gle', '-device', self.format, '-output', filename+'_SA_.'+self.format, filename+'_SA_.gle'] pid,stdin,stdout,stderr = spawn_async(glecall, flags=SPAWN_DO_NOT_REAP_CHILD) return pid
def waveform(self, filename, wavfile, framerate, msmode=False, minX=None,maxX=None,minY=None,maxY=None): numPoints = len(wavfile) rawResolution = 0.2*numPoints/self.width skip = 1 if rawResolution > self.resolution: skip = int(floor(float(rawResolution)/self.resolution)) if skip < 1: skip = 1 skip = 1 timescale = 1 if msmode: timescale = 1000 FILE = open(filename+'_SA_.dat', 'w') count = 0 for i in wavfile: if count % skip == 0: FILE.write(str(timescale*count/float(framerate))+",") FILE.write(str(i)+"\n") count = count + 1 FILE.close() if minX != None and maxX != None: if minX >= maxX: maxX = minX+1 if minX == None: minX = 0 if maxX == None: maxX = float(len(wavfile))/framerate s = ['size '+str(self.width)+' '+str(self.height)] s.append('set font psh') s.append('set hei 0.4') s.append('begin graph') s.append('nobox') s.append('x2axis off') s.append('y2axis off') if msmode: s.append('xtitle "Time (ms)"') else: s.append('xtitle "Time (s)"') s.append('ytitle " "') s.append('xticks length -0.1') s.append('yticks length -0.1') s.append('title ""') s.append('xaxis min '+str(minX)+' max '+str(maxX)) s.append('data "'+filename.rsplit('/')[-1]+'_SA_.dat"') s.append('d1 line') s.append('end graph') FILE = open(filename+'_SA_.gle', 'w') FILE.writelines('\n'.join(s)) FILE.close() glecall = ['/usr/bin/gle', '-device', self.format, '-output', filename+'_SA_.'+self.format, filename+'_SA_.gle'] pid,stdin,stdout,stderr = spawn_async(glecall, flags=SPAWN_DO_NOT_REAP_CHILD) return pid
def InstallPackageName (self, xid, timestamp, name): glib.spawn_async ([self.gpk_install_package_name, name])
def send_to(self, action, shell): entries = shell.props.selected_source.get_entry_view().get_selected_entries() cmdline = ['nautilus-sendto'] + [entry.get_playback_uri() for entry in entries] glib.spawn_async(argv=cmdline, flags=glib.SPAWN_SEARCH_PATH)