def test_file_readline_utf8(self): ch = GLib.IOChannel(filename=self.testutf8) self.assertEqual(ch.get_encoding(), 'UTF-8') self.assertTrue(ch.get_close_on_unref()) self.assertEqual(ch.readline(), 'hello ♥ world\n') self.assertEqual(ch.get_buffer_condition(), GLib.IOCondition.IN) self.assertEqual(ch.readline(), 'second line\n') self.assertEqual(ch.readline(), '\n') self.assertEqual(ch.readline(), 'À demain!') self.assertEqual(ch.get_buffer_condition(), 0) self.assertEqual(ch.readline(), '') ch.shutdown(True)
def async_list_windows(self, callback): stdout = glib_wrappers.async_run_subprocess(self.LIST_WINDOWS_COMMAND) io = GLib.IOChannel(stdout) def list_windows_callback(*_, **__): output = io.read() windows = self.parse_wlist_output(output) icons = self._get_icons() for window in windows: window.icon = icons.get(window.xid, None) callback(windows) io.add_watch(GLib.IO_IN | GLib.IO_HUP, list_windows_callback)
def __init__(self): global tag_list # configuração da porta serial #self.tela = tela self.serial_port = '/dev/ttyUSB0' self.port_speed = 9600 self.max_bytes = -1 self.ser = serial.Serial(self.serial_port, self.port_speed, timeout=3) #------------------------------------------------------------------ self.channel = GLib.IOChannel(self.ser.fileno()) self.channel.set_flags(GLib.IO_FLAG_NONBLOCK) self.cond = GLib.IOCondition(GLib.IOCondition.IN) self.channel.add_watch(self.cond,self.leituraRFID)
def test_iochannel_win32(): fd, fn = tempfile.mkstemp() closed = False try: channel = GLib.IOChannel(hwnd=fd) try: assert channel.read() == b"" finally: closed = True channel.shutdown(True) finally: if not closed: os.close(fd) os.remove(fn)
def get_lock(self): self._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) try: # Bind socket to an abstract socket address. self._lock_socket.bind('\0' + WM_CLASS) # Attach a listener to glib's event loop. GLib.io_add_watch(GLib.IOChannel(self._lock_socket.fileno()), 0, GLib.IOCondition.IN, self.toggle_listener, self._lock_socket) except socket.error: # Since the address was already taken, connect to it and send the toggle-signal. self._lock_socket.connect('\0' + WM_CLASS) self._lock_socket.send(TOGGLE_INSTRUCTION.encode()) sys.exit()
def glib_sigchld_signal_handler(callback, data=None): pipes = os.pipe() fcntl.fcntl(pipes[0], fcntl.F_SETFD, fcntl.FD_CLOEXEC) fcntl.fcntl(pipes[1], fcntl.F_SETFD, fcntl.FD_CLOEXEC) sigchld_signal_handler(_giochannel_notice_sigchld_signal, pipes[1]) channel = GLib.IOChannel(pipes[0]) channel.set_flags(GLib.IOFlags.NONBLOCK) if gi.version_info < (3, 7, 2): channel.add_watch(GLib.IOCondition.IN, _gsource_handle_signal, (callback, data)) else: GLib.io_add_watch(channel, GLib.PRIORITY_DEFAULT, GLib.IOCondition.IN, _gsource_handle_signal, (callback, data))
def _checkisoStdoutWatcher(self, fd, condition): if condition == GLib.IOCondition.HUP: return False channel = GLib.IOChannel(fd) line = channel.readline().strip() if not line.isdigit(): return True pct = float(line) / 100 if pct > 1.0: pct = 1.0 self.progressBar.set_fraction(pct) return True
def test_fd_write(self): (r, w) = os.pipe() fcntl.fcntl(r, fcntl.F_SETFL, fcntl.fcntl(r, fcntl.F_GETFL) | os.O_NONBLOCK) ch = GLib.IOChannel(filedes=w, mode='w') ch.set_encoding(None) ch.set_buffered(False) ch.write(b'\x01\x02') self.assertEqual(os.read(r, 10), b'\x01\x02') # now test blocking case, after closing the write end fcntl.fcntl(r, fcntl.F_SETFL, fcntl.fcntl(r, fcntl.F_GETFL) & ~os.O_NONBLOCK) ch.write(b'\x03\x04') ch.shutdown(True) self.assertEqual(os.read(r, 10), b'\x03\x04') os.close(r)
def test_seek(self): ch = GLib.IOChannel(filename=self.testutf8) ch.seek(2) self.assertEqual(ch.read(3), b'llo') ch.seek(2, 0) # SEEK_SET self.assertEqual(ch.read(3), b'llo') ch.seek(1, 1) # SEEK_CUR, skip the space self.assertEqual(ch.read(3), b'\xe2\x99\xa5') ch.seek(2, 2) # SEEK_END # FIXME: does not work currently #self.assertEqual(ch.read(2), b'n!') # invalid whence value self.assertRaises(ValueError, ch.seek, 0, 3)
def test_fd_read(self): (r, w) = os.pipe() ch = GLib.IOChannel(filedes=r) ch.set_encoding(None) ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) self.assertNotEqual(ch.get_flags() | GLib.IOFlags.NONBLOCK, 0) self.assertEqual(ch.read(), b'') os.write(w, b'\x01\x02') self.assertEqual(ch.read(), b'\x01\x02') # now test blocking case, after closing the write end ch.set_flags(GLib.IOFlags(ch.get_flags() & ~GLib.IOFlags.NONBLOCK)) os.write(w, b'\x03\x04') os.close(w) self.assertEqual(ch.read(), b'\x03\x04') ch.close()
def copy_files(self, file_name, action): if action == 'make_backup': command = ['cp', '-R', self.winetricks_cache + '/' + file_name, self.winetricks_cache_backup] elif action == 'restore_backup': command = ['cp', '-R', self.winetricks_cache_backup + '/' + file_name, self.winetricks_cache] self.pid, stdin, stdout, stderr = GLib.spawn_async(command, flags=GLib.SpawnFlags.SEARCH_PATH|GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) io = GLib.IOChannel(stdout) self.source_id_out = io.add_watch(GLib.IO_IN|GLib.IO_HUP, self.watch_process, 'copy_files', priority=GLib.PRIORITY_HIGH)
def __init__(self): super(Example, self).__init__() self.darea = Gtk.DrawingArea() self.darea.connect("draw", self.on_draw) self.add(self.darea) self.set_title("specanal / drygalki") self.resize(300, 200) self.set_position(Gtk.WindowPosition.CENTER) self.connect("delete-event", Gtk.main_quit) stdin = GLib.IOChannel(sys.stdin.fileno()) stdin.add_watch(GLib.IO_IN, self.on_data_ready, priority=GLib.PRIORITY_HIGH) # init spectrum analyzer: # input: # s16le 2ch 48000Hz # output: # 50Hz <-> 16kHz # total 28 bars # chunk length: # 50ms self.sa = specanal.specanal('s16le', 48000, 2, 50, 16000, 28, 50) self.sa_sfc = cairo.ImageSurface(cairo.FORMAT_RGB24, 200, 64) self.sa_ctx = cairo.Context(self.sa_sfc) # init drygalki: # input: # s16le 2ch 48000Hz # output: # 100 points # chunk length: # 50ms self.dg = drygalki.drygalki('s16le', 48000, 2, 100, 50) self.dg_sfc = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 20) self.dg_ctx = cairo.Context(self.dg_sfc) self.dg_ctx.set_line_width(1) self.buffer = b'' self.show_all()
def test_deprecated_add_watch_with_data(self): (r, w) = os.pipe() ch = GLib.IOChannel(filedes=r) ch.set_encoding(None) ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) cb_reads = [] def cb(channel, condition, data): self.assertEqual(channel, ch) self.assertEqual(condition, GLib.IOCondition.IN) self.assertEqual(data, 'hello') cb_reads.append(channel.read()) if len(cb_reads) == 2: ml.quit() return True with warnings.catch_warnings(record=True) as warn: warnings.simplefilter('always') id = GLib.io_add_watch(ch, GLib.IOCondition.IN, cb, 'hello', priority=GLib.PRIORITY_HIGH) self.assertTrue( issubclass(warn[0].category, PyGIDeprecationWarning)) ml = GLib.MainLoop() self.assertEqual(ml.get_context().find_source_by_id(id).priority, GLib.PRIORITY_HIGH) def write(): os.write(w, b'a') GLib.idle_add(lambda: os.write(w, b'b') and False) GLib.idle_add(write) GLib.timeout_add(2000, ml.quit) ml.run() self.assertEqual(cb_reads, [b'a', b'b'])
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 test_add_watch_with_multi_data(self): (r, w) = os.pipe() ch = GLib.IOChannel(filedes=r) ch.set_encoding(None) ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) cb_reads = [] def cb(channel, condition, data1, data2, data3): self.assertEqual(channel, ch) self.assertEqual(condition, GLib.IOCondition.IN) self.assertEqual(data1, 'a') self.assertEqual(data2, 'b') self.assertEqual(data3, 'c') cb_reads.append(channel.read()) if len(cb_reads) == 2: ml.quit() return True id = GLib.io_add_watch(ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb, 'a', 'b', 'c') ml = GLib.MainLoop() self.assertEqual(ml.get_context().find_source_by_id(id).priority, GLib.PRIORITY_HIGH) def write(): os.write(w, b'a') GLib.idle_add(lambda: os.write(w, b'b') and False) GLib.idle_add(write) GLib.timeout_add(2000, ml.quit) ml.run() self.assertEqual(cb_reads, [b'a', b'b'])
def process(self, widget, data=None): # params = ['du', '--si', '/'] params = [ "pocketsphinx_continuous", '-hmm', "/home/mgreibus/src/liepa/mgreibus/impl/models/hmm/liepa.cd_semi_200", "-jsgf", "/home/mgreibus/src/liepa/mgreibus/impl/lm/browser-min.gram", "-dict", "/home/mgreibus/src/liepa/mgreibus/impl/models/dict/browser.dict" ] def scroll_to_end(textview): i = textview.props.buffer.get_end_iter() mark = textview.props.buffer.get_insert() textview.props.buffer.place_cursor(i) textview.scroll_to_mark(mark, 0.0, True, 0.0, 1.0) def write_to_textview(io, condition, tw): if condition is GLib.IO_HUP: GLib.source_remove(self.source_id_out) GLib.source_remove(self.source_id_err) return False line = io.readline() tw.props.buffer.insert_at_cursor(line) scroll_to_end(tw) while Gtk.events_pending(): Gtk.main_iteration_do(False) return True def write_to_textview_out(io, condition, tw): if condition is GLib.IO_HUP: GLib.source_remove(self.source_id_out) GLib.source_remove(self.source_id_err) return False line = io.readline() processLine(line) tw.props.buffer.insert_at_cursor(line) scroll_to_end(tw) while Gtk.events_pending(): Gtk.main_iteration_do(False) return True def processLine(line): if re.search('READY...', line): wh = self.wordHeard.lower() #wts = self.wordToSay.lower() recognitionRate = u"0" #if self.totalWords > 0: # recognitionRate = u'teisingai %d iš %d' % (self.correctWords, self.totalWords) label = u'<span foreground="green" size="xx-large">Pasakyta: ' + wh.decode( 'UTF-8') + '</span>' self.label.set_markup(label) else: match = re.search('^\d+: ([\s\wąčęėįšųūžĄČĘĖĮŠŲŪŽ]+)$', line) if not match is None: #self.totalWords = self.totalWords +1 self.wordHeard = match.group(1) wh = self.wordHeard.strip().lower() if "važiuok aukščiau" == wh: tn.write("window.scrollBy(0,-200);\n") elif "važiuok žemiau" == wh: tn.write("window.scrollBy(0,200);\n") if "važiuok į pradžią" == wh: tn.write("window.scrollBy(0,-window.pageYOffset);\n") elif "važiuok į galą" == wh: tn.write( "window.scrollTo(0,document.body.scrollHeight);;\n" ) elif "atverk kortelę" == wh: tn.write("tab-new\n") elif "užverk kortelę" == wh: tn.write("tab-close\n") elif "praeita kortelė" == wh: tn.write("tab-prev\n") elif "tolimesnė kortelė" == wh: tn.write("tab-next\n") elif "užverk visas korteles" == wh: tn.write("closealltab\n") elif "atverk naują langą" == wh: tn.write("window-new\n") elif "atverk ieškos puslapį" == wh: tn.write("tab-new http://online.lt/\n") elif "perkrauk tinklapį" == wh: tn.write("location.reload();\n") elif "stabdyk krovimą" == wh: tn.write("page-stop\n") elif "rodyk visame ekrane" == wh: tn.write("fullscreen\n") elif "rodyk įprastą ekraną" == wh: tn.write("full-regular\n") elif "spausdink tinklapį" == wh: tn.write("window.print()\n") elif "rodyk sportą" == wh: tn.write("tab-new www.lrt.lt/sportas\n") elif "rodyk paštą naršyklėje" == wh: tn.write("tab-new one.lt\n") elif "rodyk filmus" == wh: tn.write("tab-new youtu.be\n") elif "rodyk muziką" == wh: tn.write("tab-new rock.lt\n") elif "rodyk naujienas" == wh: tn.write("tab-new www.lrt.lt/naujienos\n") elif "rodyk orus" == wh: tn.write("tab-new meteo.lt\n") elif "rodyk draugus" == wh: tn.write("tab-new klase.lt\n") #wts = self.wordToSay.strip().lower() #print (wh, wts) #if ud.normalize('NFC', wh) == ud.normalize('NFC',wts) : #if wh == wts : # self.correctWords = self.correctWords +1 #self.wordToSay = random.choice(wordList).encode('UTF-8') #wts = self.wordToSay #wts = wts.lower() #recognitionRate = u'teisingai %d iš %d' % (self.correctWords, self.totalWords) label = u'<span foreground="green" size="xx-large">Pasakyta: ' + wh.decode( 'UTF-8') + '</span>' self.label.set_markup(label) self.pid, stdin, stdout, stderr = GLib.spawn_async( params, flags=GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) self.progress.set_text('Runnig du --si') io = GLib.IOChannel(stdout) err = GLib.IOChannel(stderr) self.source_id_out = io.add_watch(GLib.IO_IN | GLib.IO_HUP, write_to_textview_out, self.tw_out, priority=GLib.PRIORITY_HIGH) self.source_id_err = err.add_watch(GLib.IO_IN | GLib.IO_HUP, write_to_textview, self.tw_err, priority=GLib.PRIORITY_HIGH) timeout_id = GLib.timeout_add(100, self.update_progress) def closure_func(pid, status, data): GLib.spawn_close_pid(pid) GLib.source_remove(timeout_id) self.progress.set_fraction(0.0) GLib.child_watch_add(self.pid, closure_func, None)
return True print "@PROJECT_PRETTY_NAME@ @PROJECT_VERSION@" data = Data() fd = sys.stdin.fileno() old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, new) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) io_stdin = GLib.IOChannel(fd) io_stdin.add_watch(GLib.IO_IN, handle_keyboard, data) try: erase_line() display_prompt() sys.stdout.flush() main_loop = GObject.MainLoop() main_loop.run() except KeyboardInterrupt: sys.exit() finally: termios.tcsetattr(fd, termios.TCSAFLUSH, old) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) print "" sys.exit()
def test_iochannel(): with pytest.raises(TypeError): GLib.IOChannel()
def create_progress(self, command_string): message_text = _("Processing...") window_progress = Gtk.Window( title = "Games Nebula", icon = app_icon, type = Gtk.WindowType.TOPLEVEL, window_position = Gtk.WindowPosition.CENTER_ALWAYS, resizable = False ) box = Gtk.Box( orientation = Gtk.Orientation.HORIZONTAL, spacing = 10 ) pic = app_icon.scale_simple(32, 32, InterpType.BILINEAR) image = Gtk.Image( pixbuf = pic, margin_left = 10, margin_right = 10 ) label = Gtk.Label( label = message_text, margin_right = 10, margin_top = 20, margin_bottom = 20 ) box.pack_start(image, True, True, 0) box.pack_start(label, True, True, 0) window_progress.add(box) window_progress.show_all() def watch_process(io, condition, process_name): if condition is not GLib.IO_IN: sys.exit() while Gtk.events_pending(): Gtk.main_iteration_do(False) line = io.readline() print(line.replace('\n', '')) return True if ' ' in command_string: command = command_string.split(' ') else: command = [] command.append(command_string) pid, stdin, stdout, stderr = GLib.spawn_async(command, flags=GLib.SpawnFlags.SEARCH_PATH|GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) io = GLib.IOChannel(stdout) self.source_id_out = io.add_watch(GLib.IO_IN|GLib.IO_HUP, watch_process, 'run_command', priority=GLib.PRIORITY_HIGH)
#da.add_tick_callback(redraw) #new_gdk_window() #gl.connect('render',render.gl_render) #gl.connect('realize', area_realize) daxid=da.get_window().get_xid() r=da.get_allocated_size().allocation print("%d %d %d %d\n" % (r.x, r.y, r.width, r.height)) dpy=Gdk.Display.get_default().get_xdisplay() print("python dpy=",dpy," win=",daxid) #print ([a for a in dir(dpy)]) import scope scope.get_egl_ctx(dpy,daxid) import render import sys sys.path.append('../../rawcamII') import rawcam cam_src = GLib.IOChannel(camera_init()) GLib.io_add_watch(cam_src,GLib.IO_IN,got_camera) #root=Gdk.get_default_root_window() #scr=Gdk.Display.get_default_screen() Gtk.main() exit() import cProfile GLib.timeout_add(30000, Gtk.main_quit, None) pr = cProfile.Profile() pr.enable() Gtk.main() pr.disable() pr.print_stats(sort="cumtime")
def start(self, peer, buffersync): self._gsock = mkgsock(peer) self._keepalive = KeepAlive(self._gsock, peer, "data") ioc = GLib.IOChannel(self._gsock.get_fd()) self._ioc_sig = GLib.io_add_watch(ioc, GLib.IO_IN, self._data) self._buffersync = buffersync