def test_pickle(self): def check_pickle(e): assert isinstance(e, GLib.Error) new_e = pickle.loads(pickle.dumps(e)) assert type(new_e) is type(e) assert repr(e) == repr(new_e) e = GLib.Error('test message', 'mydomain', 42) check_pickle(e) try: GLib.file_get_contents("") except Exception as e: check_pickle(e)
def finish_initializing(self, builder): """Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a SettingsDialog object with it in order to finish initializing the start of the new SettingsDialog instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self) self.check = self.builder.get_object('checkbutton_sound') # Write the file first time userpath = GLib.get_user_data_dir() fullpath = userpath + "/pomidor/config" # read file and set False or True to self.check.set_active() # try to get the data from the file if it exists try: success, text = GLib.file_get_contents(fullpath) if success and text == "True": self.check.set_active(True) else: self.check.set_active(False) except Exception: print "There is no file!"
def get_contents(*fn, dtype=str, default=None): try: ok, data = GLib.file_get_contents(os.path.join(*fn)) if not ok: return default elif dtype is bytes: return data else: return dtype(data.decode('utf8').strip()) except: return default
def __init__(self, filename): GtkSource.Buffer.__init__(self) self.filename = filename (ret, data) = GLib.file_get_contents(self.filename) assert ret self.set_language( GtkSource.LanguageManager.get_default().get_language('markdown')) self.set_text(data.strip()) self.set_modified(False)
def on_mnu_open_activate(self, widget, data=None): #get the name of the document to open title = self.ui.entry1.get_text() text = "" #create the filename data_dir = GLib.get_user_data_dir() jotty_dir = os.path.join(data_dir, "jotty") filename = os.path.join(jotty_dir, title) #try to get the data from the file if it exists try: success, text = GLib.file_get_contents(filename) except Exception: text = "" #set the UI to display the string buff = self.ui.textview1.get_buffer() buff.set_text(text)
def check_logind_gnome_session(self): '''Check that gnome-session is built with logind support''' path = GLib.find_program_in_path ('gnome-session') assert(path) (success, data) = GLib.file_get_contents (path) lines = data.split('\n') new_path = None for line in lines: items = line.split() if items and items[0] == 'exec': new_path = items[1] if not new_path: self.fail("could not get gnome-session's real path from %s" % path) path = new_path ldd = subprocess.Popen(['ldd', path], stdout=subprocess.PIPE) out = ldd.communicate()[0] if not 'libsystemd.so.0' in out: self.fail('gnome-session is not built with logind support')
def check_logind_gnome_session(self): '''Check that gnome-session is built with logind support''' path = GLib.find_program_in_path('gnome-session') assert (path) (success, data) = GLib.file_get_contents(path) lines = data.split('\n') new_path = None for line in lines: items = line.split() if items and items[0] == 'exec': new_path = items[1] if not new_path: self.fail("could not get gnome-session's real path from %s" % path) path = new_path ldd = subprocess.Popen(['ldd', path], stdout=subprocess.PIPE) out = ldd.communicate()[0] if not 'libsystemd.so.0' in out: self.fail('gnome-session is not built with logind support')
def handle_download_request(self, message, path): # could handle multiple files here ... if path != "/1" or not self.shared_file: self.reply_request(message, Status.NOT_FOUND, FormInfo.DOWNLOAD_NOT_FOUND) return if self.archive_state == ArchiveState.PREPARING: self.reply_request(message, Status.ACCEPTED, FormInfo.PREPARING_DOWNLOAD) return shared_content = GLib.file_get_contents(self.shared_file)[1] message.set_status(Status.OK) attachment = {"filename": GLib.path_get_basename(self.shared_file)} message.response_headers.set_content_disposition("attachment", attachment) message.response_body.append_buffer(Soup.Buffer.new(shared_content)) message.connect("wrote-body", self.on_soup_message_wrote_body) self.download_count += 1 self.change_callback()
def open_file(self, widget): open_dialog = Gtk.FileChooserDialog( "Open an existing file", self, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) open_response = open_dialog.run() if open_response == Gtk.ResponseType.OK: filename = open_dialog.get_filename() buf = self.mytext.get_buffer() des_tag_format = buf.register_deserialize_tagset() des_content = GLib.file_get_contents(filename) text = buf.deserialize(buf, des_tag_format, buf.get_start_iter(), des_content) self.mytext.get_buffer().set_text(text) open_dialog.destroy() elif open_response == Gtk.ResponseType.CANCEL: print("Cancel clicked") open_dialog.destroy()
def play(self): # Show notification // NOTE for translation _("Stirng") n = Notify.Notification.new(_("Pomidor Time Manager"), _("Time is up!"), self.image) if not n.show(): raise Exception(_("Could not show notification...")) # Optionally play sound. File is created when window is initialized above userpath = GLib.get_user_data_dir() fullpath = userpath + "/pomidor/config" # plus app path try: success, text = GLib.file_get_contents(fullpath) if success and text == "True": canberra = pycanberra.Canberra() canberra.easy_play_sync("service-login") canberra.destroy() else: pass except Exception: print "There is no config file!"
def on_mnu_open_activate(self, widget, data=None): print "openning" #get the name of the document to open opener = OpenDialog() result = opener.run() filename = opener.selected_file #close the dialog, and check whether to proceed opener.destroy() if result != Gtk.ResponseType.OK: return #try to get the data from the file if it exists try: success, text = GLib.file_get_contents(filename) except Exception: text = "" print text #set the UI to display the string buff = self.ui.textview1.get_buffer() buff.set_text(text)
def selection_cb(self, selection, model): sel = selection.get_selected() if sel == (): return treeiter = sel[1] demo = model.get_value(treeiter, 1) title = demo.title if demo.isdir: return description = demo.module.description code = GLib.file_get_contents(demo.filename)[1] # output and style the title (start, end) = self.info_buffer.get_bounds() self.info_buffer.delete(start, end) (start, end) = self.source_buffer.get_bounds() self.source_buffer.delete(start, end) start = self.info_buffer.get_iter_at_offset(0) end = start.copy() self.info_buffer.insert(end, title) start = end.copy() start.backward_chars(len(title)) self.info_buffer.apply_tag_by_name("title", start, end) self.info_buffer.insert(end, "\n\n") # output the description self.info_buffer.insert(end, description) # output the code start = self.source_buffer.get_iter_at_offset(0) end = start.copy() self.source_buffer.insert(end, code)
def selection_cb(self, selection, model): sel = selection.get_selected() if sel == (): return treeiter = sel[1] demo = model.get_value(treeiter, 1) title = demo.title if demo.isdir: return description = demo.module.description code = GLib.file_get_contents(demo.filename)[1] # output and style the title (start, end) = self.info_buffer.get_bounds() self.info_buffer.delete(start, end) (start, end) = self.source_buffer.get_bounds() self.source_buffer.delete(start, end) start = self.info_buffer.get_iter_at_offset(0) end = start.copy() self.info_buffer.insert(end, title) start = end.copy() start.backward_chars(len(title)) self.info_buffer.apply_tag_by_name('title', start, end) self.info_buffer.insert(end, '\n\n') # output the description self.info_buffer.insert(end, description) # output the code start = self.source_buffer.get_iter_at_offset(0) end = start.copy() self.source_buffer.insert(end, code)
def on_button3_clicked(self, widget, data=None): print "open button action called" dialog = Gtk.FileChooserDialog("Please choose a file", self, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) self.add_filters(dialog) response = dialog.run() if response == Gtk.ResponseType.OK: print "Open clicked" filename=dialog.get_filename() filetitle=os.path.basename(filename) self.ui.entry1.set_text(filetitle) print filename text = GLib.file_get_contents(filename) buff = self.ui.textview1.get_buffer() buff.set_text(text[1]) elif response == Gtk.ResponseType.CANCEL: print "Cancel clicked" dialog.destroy()
def get_brightness(self): try: (success, ret) = GLib.file_get_contents ('GSD_MOCK_brightness') except: return gsdpowerconstants.GSD_MOCK_DEFAULT_BRIGHTNESS return int(ret)
def do_execute_async(self, cancellable, callback, data): if self.mode == _MODE_INSTALL: self.props.title = _('Installing rustup') elif self.mode == _MODE_UPDATE: self.props.title = _('Updating rustup') elif self.mode == _MODE_INSTALL_TOOLCHAIN: self.props.title = _('Installing rust ') + self.toolchain self.props.status = _('Checking system') self.props.icon_name = 'emblem-system-symbolic' self.state = _STATE_INIT self.downloaded_components = 0 self.installed_components = 0 task = Gio.Task.new(self, cancellable, callback) launcher = Ide.SubprocessLauncher.new(0) launcher.set_clear_env(False) launcher.set_run_on_host(True) launcher.set_cwd(GLib.get_home_dir()) stdin_data = None if self.mode == _MODE_INSTALL: # Because our script is inside the application mount namespace, and we # need to execute this on the host (via the subprocess helper), we need # to execute it using bash and reading from stdin. launcher.push_argv('bash') launcher.push_argv('--') launcher.push_argv('/dev/stdin') launcher.push_argv('-y') try: rustup_sh_path = get_module_data_path('resources/rustup.sh') success, stdin_data = GLib.file_get_contents(rustup_sh_path) except: stdin_data = "" elif self.mode == _MODE_UPDATE: launcher.push_argv(RustupApplicationAddin.instance.rustup_executable) launcher.push_argv('update') elif self.mode == _MODE_INSTALL_TOOLCHAIN: launcher.push_argv(RustupApplicationAddin.instance.rustup_executable) launcher.push_argv('toolchain') launcher.push_argv('install') launcher.push_argv(self.toolchain) # rustup needs a tty to give us a progress bar (master_fd, slave_fd) = pty.openpty() launcher.take_stdin_fd(os.dup(slave_fd)) launcher.take_stdout_fd(os.dup(slave_fd)) launcher.take_stderr_fd(os.dup(slave_fd)) launcher.setenv('TERM', 'xterm-256color', True) data_stream = Gio.DataInputStream.new(Gio.UnixInputStream.new(os.dup(master_fd), True)) # set it to ANY so the progress bars can be parsed data_stream.set_newline_type(Gio.DataStreamNewlineType.ANY) data_stream.read_line_async(GLib.PRIORITY_DEFAULT, cancellable, self._read_line_cb, cancellable) task.connect('notify::completed', close_fds, (master_fd, slave_fd)) try: # pass cancellable so that if cancelled, the process force exits sub_process = launcher.spawn(cancellable) if stdin_data: os.write(master_fd, stdin_data) sub_process.wait_async(cancellable, self._wait_cb, task) except Exception as ex: print(repr(ex)) task.return_error(GLib.Error(message=repr(ex)))
def check_current(): if (glib.file_test('/etc/prime/current_type', glib.FileTest.EXISTS)): return glib.file_get_contents('/etc/prime/current_type')[1].decode("utf-8").strip() else: return ''
def get_brightness(self): try: (success, ret) = GLib.file_get_contents('GSD_MOCK_brightness') except: return gsdpowerconstants.GSD_MOCK_DEFAULT_BRIGHTNESS return int(ret)
def test_gerror(self): callable_ = lambda: GLib.file_get_contents('/nonexisting ') self.assertRaises(GLib.GError, testhelper.test_gerror_exception, callable_)
def test_no_gerror(self): callable_ = lambda: GLib.file_get_contents(__file__) self.assertEqual(testhelper.test_gerror_exception(callable_), None)