def __init__(self): self.pipeline = Gst.Pipeline() self.videomixer = Gst.ElementFactory.make('videomixer', 'videomixer') self.pipeline.add(self.videomixer) for uri in ( "http://video.blendertestbuilds.de/download.blender.org/ED/ED_1280.avi", "http://download.blender.org/durian/trailer/sintel_trailer-720p.mp4", ): decoder = Gst.ElementFactory.make('uridecodebin', 'uridecoder(' + uri + ')') decoder.set_property("uri", uri) decoder.connect("pad-added", self.OnDynamicPad) self.pipeline.add(decoder) self.decoder.append(decoder) self.monitorvideosink = Gst.ElementFactory.make( 'autovideosink', 'monitorvideosink') self.pipeline.add(self.monitorvideosink) self.videomixer.link(self.monitorvideosink) self.monitoraudiosink = Gst.ElementFactory.make( 'autoaudiosink', 'monitoraudiosink') self.pipeline.add(self.monitoraudiosink) self.pipeline.set_state(Gst.State.PLAYING) GLib.io_add_watch(sys.stdin, GLib.IO_IN, self.Input)
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 as 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) GLib.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) GLib.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 = self.input_text if self.idle_write_chunk(): self.idle_write_id = GLib.idle_add(self.idle_write_chunk) # Wait for the process to complete GLib.child_watch_add(self.pipe.pid, self.on_child_end)
def reset(self): self.repo.state[0] = STATE_RESETTING cmd = "git reset --hard" self.process = subprocess.Popen(cmd, cwd=self.repo.dir, stdout=subprocess.PIPE, stderr=STDOUT, shell=True, preexec_fn=os.setsid) GLib.io_add_watch(self.process.stdout, GLib.IO_IN, self.output_callback)
def __init__(self, w, h, child_conn): super(MainWindow, self).__init__(title="RayTracingOpenCL") self.child_conn = child_conn self.w, self.h = w, h self.already_pressed = { k: False for k in [ "w", "a", "s", "d", "Up", "Left", "Right", "Down", "Escape", "q", "e", "plus", "minus" ] } vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.image = Gtk.Image() vbox.pack_start(self.image, True, True, 0) self.status = Gtk.Label() vbox.pack_start(self.status, False, True, 0) self.add(vbox) self.connect("key-press-event", self.on_key_pressed) self.connect("key-release-event", self.on_key_released) GLib.io_add_watch(GLib.IOChannel(self.child_conn.fileno()), GLib.PRIORITY_DEFAULT_IDLE, GLib.IOCondition(1 | 8 | 16), self.on_new_frame_ready, None) self.start = datetime.datetime.now() self.fps = 0
def __init__(self, cmd, resultHandler, prio=GObject.PRIORITY_LOW): self.lineSplitter = LineSplitter(resultHandler) #print("executing command: %s" % cmd) self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, close_fds=True) self.pipe = self.proc.stdout # make pipe non-blocking: fl = fcntl.fcntl(self.pipe, fcntl.F_GETFL) fcntl.fcntl(self.pipe, fcntl.F_SETFL, fl | os.O_NONBLOCK) #print "(add watch)" if GObject.pygobject_version < (3, 7, 2): GObject.io_add_watch(self.pipe, GObject.IO_IN | GObject.IO_ERR | GObject.IO_HUP, self.onPipeReadable, priority=prio) else: # avoid deprecation warning in newer versions of PyGObject: GLib.io_add_watch(self.pipe, prio, GLib.IO_IN | GLib.IO_ERR | GLib.IO_HUP, self.onPipeReadable)
def test_io_add_watch_with_data(self): (r, w) = os.pipe() call_data = [] def cb(fd, condition, data): call_data.append((fd, condition, os.read(fd, 1), data)) if len(call_data) == 2: ml.quit() return True # io_add_watch() takes an IOChannel, calling with an fd is deprecated with warnings.catch_warnings(record=True) as warn: warnings.simplefilter('always') GLib.io_add_watch(r, GLib.IOCondition.IN, cb, 'moo', priority=GLib.PRIORITY_HIGH) self.assertTrue( issubclass(warn[0].category, PyGIDeprecationWarning)) def write(): os.write(w, b'a') GLib.idle_add(lambda: os.write(w, b'b') and False) ml = GLib.MainLoop() GLib.idle_add(write) GLib.timeout_add(2000, ml.quit) ml.run() self.assertEqual(call_data, [(r, GLib.IOCondition.IN, b'a', 'moo'), (r, GLib.IOCondition.IN, b'b', 'moo')])
def on_msg_write(self, source, condition): # Ensure socket is alive if self.sock is None: return False bytes_sent = 0 write_buffer = ''.join(self.write_buffer) del self.write_buffer[:] bytes_total = len(write_buffer) try: while bytes_sent < MAX_WRITE_BATCH_SIZE: data = write_buffer[bytes_sent:bytes_sent + CHUNK_SIZE] if len(data) == 0: break self.sock.send(data) bytes_sent += len(data) except socket.error as error: if error.errno == errno.EAGAIN: return True elif self._handle_connection_error(error): GLib.io_add_watch(self.sock.fileno(), GLib.IO_OUT, self.on_msg_write, priority=GLib.PRIORITY_LOW) return False else: self.writing = False return False else: self.writing = bytes_sent < bytes_total return self.writing finally: self.write_buffer = [write_buffer[bytes_sent:], ]
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) = GLib.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 GLib.child_watch_add(GLib.PRIORITY_DEFAULT, self.helper_pid, self._on_x2go_exit) # Add a watch on stdout channel = GLib.IOChannel.unix_new(self.helper_stdout) GLib.io_add_watch(channel, GLib.PRIORITY_DEFAULT, 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 listen(self): try: dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() obj = bus.get_object('org.bluez', "/") mgr = dbus.Interface(obj, 'org.freedesktop.DBus.ObjectManager') for path, ifaces in mgr.GetManagedObjects().items(): adapter = ifaces.get('org.bluez.MediaPlayer1') if not adapter: continue player = bus.get_object('org.bluez', path) self.player_iface = dbus.Interface( player, dbus_interface='org.bluez.MediaPlayer1') break if not adapter: sys.exit('Error: Media Player not found.') bus.add_signal_receiver( self.on_property_changed, bus_name='org.bluez', signal_name='PropertiesChanged', dbus_interface='org.freedesktop.DBus.Properties') GLib.io_add_watch(sys.stdin, GLib.IO_IN, self.on_playback_control) GLib.MainLoop().run() except: print("Error: ", sys.exc_info()[0])
def __init__(self, server_address, RequestHandlerClass): SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass) self.socket.setblocking(0) # Set nonblocking # Watch the listener socket for data GLib.io_add_watch(self.socket, GLib.IO_IN, self._handle_accept)
def __init__(self, port, controller, script): ''' Builds the GUI, connects it to the server (thread). The GUI is just another client of the service. ''' global cmdClient cmdClient = self self.logger = logging.getLogger(__name__) self.port = port self.controller = controller self.script = script self.prompt = '$ ' (self.stdin, self.echo) = (sys.stdin, False) if self.script == '-' else (open(script, 'r'), True) self.stdout = sys.stdout self.conn = rpyc.connect(self.controller.hostAddress, port) # Local connection to the service GLib.io_add_watch( self.conn, 1, GLib.IO_IN, self.bg_server) # Register the callback with the service GLib.io_add_watch(self.stdin, 1, GLib.IO_IN, self.cmd_server) self.conn.root.login("*gui*", self.on_serverMessage) # Log in to the service self.appDownLoaded = False self.appFolder = None self.appName = None self.deplName = None self.nodeIDDict = OrderedDict() self.appStatusDict = OrderedDict() self.loop = GLib.MainLoop()
def __init__(self, line_callback): self.buffer = '' self.line_callback = line_callback flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) flags |= os.O_NONBLOCK fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flags) GLib.io_add_watch(sys.stdin, GLib.IO_IN, self.io_callback)
def test_io_add_watch_with_data(self): (r, w) = os.pipe() call_data = [] def cb(fd, condition, data): call_data.append((fd, condition, os.read(fd, 1), data)) if len(call_data) == 2: ml.quit() return True # io_add_watch() takes an IOChannel, calling with an fd is deprecated with warnings.catch_warnings(record=True) as warn: warnings.simplefilter('always') GLib.io_add_watch(r, GLib.IOCondition.IN, cb, 'moo', priority=GLib.PRIORITY_HIGH) self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) def write(): os.write(w, b'a') GLib.idle_add(lambda: os.write(w, b'b') and False) ml = GLib.MainLoop() GLib.idle_add(write) GLib.timeout_add(2000, ml.quit) ml.run() self.assertEqual(call_data, [(r, GLib.IOCondition.IN, b'a', 'moo'), (r, GLib.IOCondition.IN, b'b', 'moo')])
def __init__(self, path): self.log = logging.getLogger('Directory') self.path = path self.scheduled = False self.rescan() self.log.debug('setting up inotify watch for %s', self.path) wm = pyinotify.WatchManager() notifier = pyinotify.Notifier( wm, timeout=10, default_proc_fun=self.inotify_callback ) wm.add_watch( self.path, # pyinotify.ALL_EVENTS, pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY, rec=True ) GLib.io_add_watch( notifier._fd, GLib.IO_IN, self.io_callback, notifier )
def __init__(self): self.__init_curses() self.__bus = IBus.Bus() self.__ic_path = self.__bus.create_input_context("DemoTerm") #self.__ic = IBus.InputContext(self.__bus, self.__ic_path, True) self.__ic = IBus.InputContext() self.__ic.set_capabilities(7) self.__ic.connect("commit-text", self.__commit_text_cb) self.__ic.connect("update-preedit-text", self.__update_preedit_text_cb) self.__ic.connect("show-preedit-text", self.__show_preedit_text_cb) self.__ic.connect("hide-preedit-text", self.__hide_preedit_text_cb) self.__ic.connect("update-auxiliary-text", self.__update_aux_text_cb) self.__ic.connect("show-auxiliary-text", self.__show_aux_text_cb) self.__ic.connect("hide-auxiliary-text", self.__hide_aux_text_cb) self.__ic.connect("update-lookup-table", self.__update_lookup_table_cb) self.__ic.connect("show-lookup-table", self.__show_lookup_table_cb) self.__ic.connect("hide-lookup-table", self.__hide_lookup_table_cb) GLib.io_add_watch(0, GLib.IO_IN, self.__stdin_cb) # GLib.timeout_add(500, self.__timeout_cb) # self.__master_fd, self.__slave_fd = os.openpty() # self.__run_shell() self.__is_invalidate = False self.__preedit = None self.__preedit_visible = False self.__aux_string = None self.__aux_string_visible = False self.__lookup_table = None self.__lookup_table_visible = False
def run(): """Run the UI.""" global loop loop = gobject.MainLoop() ui.set_mouse_tracking() app = appGUI() # Connect signals and whatnot to UI screen control functions bus.add_signal_receiver(app.dbus_scan_finished, 'SendEndScanSignal', 'org.wicd.daemon.wireless') bus.add_signal_receiver(app.dbus_scan_started, 'SendStartScanSignal', 'org.wicd.daemon.wireless') # I've left this commented out many times. bus.add_signal_receiver(app.update_netlist, 'StatusChanged', 'org.wicd.daemon') # Update the connection status on the bottom every 2 s. gobject.timeout_add(2000, app.update_status) # Get input file descriptors and add callbacks to the ui-updating function fds = ui.get_input_descriptors() for fd in fds: gobject.io_add_watch(fd, gobject.IO_IN, app.call_update_ui) app.update_ui() loop.run()
def test_io_add_watch_pyfile(self): call_data = [] cmd = subprocess.Popen('sleep 0.1; echo hello; sleep 0.2; echo world', shell=True, stdout=subprocess.PIPE) def cb(file, condition): call_data.append((file, condition, file.readline())) if len(call_data) == 2: # avoid having to wait for the full timeout ml.quit() return True # io_add_watch() takes an IOChannel, calling with a Python file is deprecated with warnings.catch_warnings(record=True) as warn: warnings.simplefilter('always') GLib.io_add_watch(cmd.stdout, GLib.IOCondition.IN, cb) self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) ml = GLib.MainLoop() GLib.timeout_add(2000, ml.quit) ml.run() cmd.wait() self.assertEqual(call_data, [(cmd.stdout, GLib.IOCondition.IN, b'hello\n'), (cmd.stdout, GLib.IOCondition.IN, b'world\n')])
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) = GLib.spawn_async(cmd, flags=GObject.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) if (Globals.DEBUG_SWITCH): LOG.debug("running: '%s' as pid: '%s'" % (cmd, pid)) # python-gobject >= 3.7.3 has changed some API in incompatible # ways, so we need to check the version for which one to use. if gi_version < (3, 7, 3): self._child_watch = GLib.child_watch_add(pid, self._helper_finished, (stdout, stderr)) self._io_watch = GLib.io_add_watch(stdout, GObject.IO_IN, self._helper_io_ready, (stdout, )) else: self._child_watch = GLib.child_watch_add(GLib.PRIORITY_DEFAULT, pid, self._helper_finished, data=(stdout, stderr)) self._io_watch = GLib.io_add_watch(stdout, GLib.PRIORITY_DEFAULT, GObject.IO_IN, self._helper_io_ready, (stdout, ))
def __init__(self): self.server_running = False self.started = False self.counter = 0 self.prev_filename = "" self.new_filename = "" self.timeout_length = VIDEO_LENGTH self.timeoutid = None self.previous_filepath = "" # # register socket for main loop self.create_socket() GLib.io_add_watch(self.socket, GLib.IO_IN, self.socket_listener) # Example shell command for signaling PID # kill -s USR1 PID GLib.unix_signal_add(1, signal.SIGINT.value, self.exit_application) # Create pipeline components self.create_video_capture_bin() self.create_main_pipeline() self.create_tcp_server_pipeline() self.create_image_capture_pipeline() # Create bus to get events from GStreamer pipeline self.bus = self.pipeline.get_bus() self.bus.add_signal_watch() self.bus.connect("message::eos", self.on_eos) self.bus.connect("message::error", self.on_error) self.bus.unref() self.loop = GLib.MainLoop()
def __init__(self, card="hw:0", name=("Master", "Speaker"), id=0, base=80, spacing=3): super().__init__() stack = Gtk.Overlay(visible=True) iconP = Gtk.DrawingArea(visible=True) self.text = Gtk.Label(visible=True) self.icon = VolumeIcon(iconP, self.text, visible=True) box = Gtk.Box(spacing=spacing, visible=True) box.pack_start(iconP, False, False, 0) box.pack_start(self.text, False, False, 0) stack.add(box) stack.add_overlay(self.icon) self.add(stack) self.base = base self.alsa = simplealsa.Alsa(card) self.volume = self.alsa.selem(name[0]) self.mute = self.alsa.selem(name[1]) self.min, self.max = self.volume.mB_range self.update_volume() self.update_mute() self.volume.callback(self.update_volume) self.mute.callback(self.update_mute) def update(*_): self.alsa.handle_events() return True for fd in self.alsa.fds(): GLib.io_add_watch(fd.fd, GLib.IO_IN, update) self.show()
def clean(self): self.repo.state[0] = STATE_CLEANING cmd = "git clean -fdx" self.process = subprocess.Popen(cmd, cwd=self.repo.dir, stdout=subprocess.PIPE, stderr=STDOUT, shell=True, preexec_fn=os.setsid) GLib.io_add_watch(self.process.stdout, GLib.IO_IN, self.output_callback)
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 self._lintian_exit_status_gathered = 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) GLib.io_add_watch(channel, GLib.PRIORITY_DEFAULT, GLib.IOCondition.IN | GLib.IO_ERR | GLib.IO_HUP, self._on_lintian_output) GLib.child_watch_add(GLib.PRIORITY_DEFAULT, pid, self._on_lintian_finished)
def __init__(self, args): '''Initialize controller and start child process The parameter args is a list of command line arguments to pass on to the child process. The "-v" argument is automatically added.''' GObject.GObject.__init__(self) # Initialize state variables self._inhibited = False self._temperature = 0 self._period = 'Unknown' self._location = (0.0, 0.0) # Start redshift with arguments args.insert(0, os.path.join(defs.BINDIR, 'redshift')) if '-v' not in args: args.insert(1, '-v') # Start child process with C locale so we can parse the output env = os.environ.copy() env['LANG'] = env['LANGUAGE'] = env['LC_ALL'] = env['LC_MESSAGES'] = 'C' self._process = GLib.spawn_async(args, envp=['{}={}'.format(k,v) for k, v in env.items()], flags=GLib.SPAWN_DO_NOT_REAP_CHILD, standard_output=True, standard_error=True) # Wrap remaining contructor in try..except to avoid that the child # process is not closed properly. try: # Handle child input # The buffer is encapsulated in a class so we # can pass an instance to the child callback. class InputBuffer(object): buf = '' self._input_buffer = InputBuffer() self._error_buffer = InputBuffer() self._errors = '' # Set non blocking fcntl.fcntl(self._process[2], fcntl.F_SETFL, fcntl.fcntl(self._process[2], fcntl.F_GETFL) | os.O_NONBLOCK) # Add watch on child process GLib.child_watch_add(GLib.PRIORITY_DEFAULT, self._process[0], self._child_cb) GLib.io_add_watch(self._process[2], GLib.PRIORITY_DEFAULT, GLib.IO_IN, self._child_data_cb, (True, self._input_buffer)) GLib.io_add_watch(self._process[3], GLib.PRIORITY_DEFAULT, GLib.IO_IN, self._child_data_cb, (False, self._error_buffer)) # Signal handler to relay USR1 signal to redshift process def relay_signal_handler(signal): os.kill(self._process[0], signal) return True GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGUSR1, relay_signal_handler, signal.SIGUSR1) except: self.termwait() raise
def startAsync(self): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() obj = bus.get_object('org.bluez', "/") mgr = dbus.Interface(obj, 'org.freedesktop.DBus.ObjectManager') self.player_iface = None self.transport_prop_iface = None for path, ifaces in mgr.GetManagedObjects().items(): if 'org.bluez.MediaPlayer1' in ifaces: self.player_iface = dbus.Interface( bus.get_object('org.bluez', path), 'org.bluez.MediaPlayer1') elif 'org.bluez.MediaTransport1' in ifaces: self.transport_prop_iface = dbus.Interface( bus.get_object('org.bluez', path), 'org.freedesktop.DBus.Properties') if not self.player_iface: sys.exit('Error: Media Player not found.') if not self.transport_prop_iface: sys.exit('Error: DBus.Properties iface not found.') self.volume = self.transport_prop_iface.Get( 'org.bluez.MediaTransport1', 'Volume') bus.add_signal_receiver( self.on_property_changed, bus_name='org.bluez', signal_name='PropertiesChanged', dbus_interface='org.freedesktop.DBus.Properties') GLib.io_add_watch(sys.stdin, GLib.IO_IN, self.on_playback_control) GLib.MainLoop().run()
def _starttls(self, sock, conv:Conversation, server_side:bool): self._dtls_prep[conv.key] = sock # Create a bound-on-both-sides socket which will preferentially # receive datagrams for this conversation conn = socket.socket(sock.family, sock.type, sock.proto) conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) conn.bind(sock.getsockname()) conn.connect(conv.get_peer_addr()) LOGGER.info('STARTTLS for %s', conv) conn = self._config.get_ssl_connection(conn, server_side=server_side) if server_side: pass # conn.listen() else: # as client conn.connect(conv.get_peer_addr()) self.__logger.info('Starting DTLS handshake on %s', sock) conn.do_handshake() # after establishment del self._dtls_prep[conv.key] self._dtls_sess[conv.key] = conn glib.io_add_watch( conn.get_socket(inbound=True), glib.IO_IN, self._dtlsconn_recv, conn, conv ) return conn
def _onResolveComplete(self, source, cb_condition, hostname, port): assert not (cb_condition & _flagError) assert source == self.asyncns.get_fd() if self.isDispose: return False # get resolve result hostaddr = None try: resq = self.asyncns.get_next() assert isinstance(resq, libasyncns.AddrInfoQuery) hostaddr, dummy = resq.get_done()[0][4] except Exception as e: self.sockSet.remove((hostname, port)) #logging.debug("SnPeerClient.connect: Resolve failed, %s, %d, %s, %s", hostname, port, e.__class__, e) return False # do connect sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) try: sock.connect((hostaddr, port)) except socket.error as e: if e.errno == errno.EAGAIN or e.errno == errno.EINPROGRESS: pass else: self.sockSet.remove((hostname, port)) #logging.debug("SnPeerClient.connect: Resolve failed, %s, %d, %s, %s", hostname, port, e.__class__, e) sock.close() return False GLib.io_add_watch(sock, GLib.IO_IN | GLib.IO_OUT | _flagError, self._onConnect, hostname, port) return False
def __init__(self, x_display: Display = None): try: self.xdisp = x_display or Display() except (UnicodeDecodeError, DisplayConnectionError) as err: raise XInitError("python-xlib failed with %s when asked to open" " a connection to the X server. Cannot bind keys." "\n\tIt's unclear why this happens, but it is" " usually fixed by deleting your ~/.Xauthority" " file and rebooting." % err.__class__.__name__) self.xroot = self.xdisp.screen().root self._keys = {} # type: Dict[Tuple[int, int], Callable] # Resolve these at runtime to avoid NameErrors self._ignored_modifiers = [ getattr(X, name) for name in self.ignored_modifiers ] # type: List[int] # We want to receive KeyPress events self.xroot.change_attributes(event_mask=X.KeyPressMask) # Set up a handler to catch XGrabKey() failures self.xdisp.set_error_handler(self.cb_xerror) # Merge python-xlib into the GLib event loop # Source: http://www.pygtk.org/pygtk2tutorial/sec-MonitoringIO.html GLib.io_add_watch(self.xroot.display, GLib.PRIORITY_DEFAULT, GLib.IO_IN, self.cb_xevent)
def run(self): self.loop = GLib.MainLoop() chan = GLib.IOChannel.unix_new(sys.stdin.fileno()) GLib.io_add_watch(chan, GLib.IOCondition.IN, self.message_handler) GLib.io_add_watch(chan, GLib.IOCondition.HUP, lambda *_: self.loop.quit()) self.loop.run()
def __init__(self, bus, index, service): Characteristic.__init__(self, bus, index, UART_BATTERY_CHARACTERISTIC_UUID, ['notify'], service) self.notifying = False GLib.io_add_watch(sys.stdin, GLib.IO_IN, self.on_console_input)
def _watch_sock(self): self.sock_info.timeout = self._conn_timeout sock = self.sock_info.get_sock() if sock is None: return False else: self.sock = sock _debug('Adding socket callbacks to GLib loop') GLib.io_add_watch( self.sock, GLib.PRIORITY_DEFAULT, GLib.IO_IN, self._socket_rdy, ) # GLib.IO_HUP is the hangup condition # i.e., if another server deletes or binds to the same socket path # Maybe?? I'm not sure if this works as expected. # https://developer.gnome.org/pygobject/stable/glib-functions.html#function-glib--io-add-watch GLib.io_add_watch( self.sock, GLib.PRIORITY_DEFAULT, GLib.IO_HUP, self._loop_quit, ) return True
def test_io_add_watch_pyfile(self): call_data = [] cmd = subprocess.Popen('sleep 0.1; echo hello; sleep 0.2; echo world', shell=True, stdout=subprocess.PIPE) def cb(file, condition): call_data.append((file, condition, file.readline())) if len(call_data) == 2: # avoid having to wait for the full timeout ml.quit() return True # io_add_watch() takes an IOChannel, calling with a Python file is deprecated with warnings.catch_warnings(record=True) as warn: warnings.simplefilter('always') GLib.io_add_watch(cmd.stdout, GLib.IOCondition.IN, cb) self.assertTrue( issubclass(warn[0].category, PyGIDeprecationWarning)) ml = GLib.MainLoop() GLib.timeout_add(2000, ml.quit) ml.run() cmd.wait() self.assertEqual(call_data, [(cmd.stdout, GLib.IOCondition.IN, b'hello\n'), (cmd.stdout, GLib.IOCondition.IN, b'world\n')])
def run(self): self.msg_receiver = common.jsonwait.JsonReceiver(self.sock) self.msg_sender = common.jsonwait.JsonSender(self.sock) GLib.io_add_watch(self.sock, GLib.IO_IN, self.__on_receive_event) self.__reset() self.control.run()
def run(self): # Set to READY and wait, get OpenGL context. self.pipeline.set_state(Gst.State.READY) self.pipeline.get_state(Gst.CLOCK_TIME_NONE) assert self.overlaysink.glcontext self.overlaysink.glcontext.thread_add(self.callback.init_gl) if sys.stdin.isatty(): fd = sys.stdin.fileno() old_mode = termios.tcgetattr(fd) new_mode = termios.tcgetattr(fd) new_mode[3] = new_mode[3] & ~(termios.ICANON | termios.ECHO) termios.tcsetattr(fd, termios.TCSANOW, new_mode) GLib.io_add_watch(sys.stdin, GLib.IO_IN, self.on_stdin) try: # Run pipeline. traceback.print_exc() self.pipeline.set_state(Gst.State.PLAYING) Gtk.main() except: pass finally: if sys.stdin.isatty(): termios.tcsetattr(fd, termios.TCSAFLUSH, old_mode) # Clean up. self.pipeline.set_state(Gst.State.READY) self.pipeline.get_state(Gst.CLOCK_TIME_NONE) self.callback.empty_trash() self.callback.running = False self.pipeline.set_state(Gst.State.NULL) while GLib.MainContext.default().iteration(False): pass
def on_msg_write(self, source, condition): # Ensure socket is alive if self.sock is None: return False bytes_sent = 0 bytes_total = len(self.write_buffer) try: while self.write_buffer and bytes_sent < MAX_WRITE_BATCH_SIZE: data = self.write_buffer[:CHUNK_SIZE] self.sock.send(data) bytes_sent += len(data) self.write_buffer = self.write_buffer[CHUNK_SIZE:] except socket.error as error: if error.errno == errno.EAGAIN: return True elif self._handle_connection_error(error): GLib.io_add_watch(self.sock.fileno(), GLib.IO_OUT, self.on_msg_write, priority=GLib.PRIORITY_LOW) return False else: self.writing = False return False else: self.writing = bytes_sent < bytes_total return self.writing
def generate_avi(self): folder_png = self.animation.get_png_dir() list_file = os.path.join(folder_png, "list") video_file = self.animation.get_avi_file() framerate = self.animation.get_framerate() if not os.path.exists(list_file): error_dlg = Gtk.MessageDialog( transient_for=self.dialog, title="Cannot continue", modal=True, destroy_with_parent=True, message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, text="In directory: %s there is no listing file" % (folder_png)) error_dlg.run() error_dlg.destroy() return if not self.converterpath: error_dlg = Gtk.MessageDialog( transient_for=self.dialog, title="Cannot continue", modal=True, destroy_with_parent=True, message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, text="Cannot find ffmpeg video conversion utility") error_dlg.run() error_dlg.destroy() return self.spinner.start() # calling ffmpeg # https://trac.ffmpeg.org/wiki/Concatenate # https://trac.ffmpeg.org/wiki/Encode/VP9 call = [ self.converterpath, "-nostdin", "-y", "-loglevel", "error", "-hide_banner", "-r", str(framerate), "-f", "concat", "-safe", "0", "-i", list_file ] if self.animation.get_redblue(): call.extend(["-vf", "colorchannelmixer=rr=0:rb=1:br=1:bb=0"]) call.extend([ "-c:v", "libvpx-vp9", "-crf", "30", "-b:v", "0", "-r", str(framerate), video_file ]) self.pid, fd_in, fd_out, fd_err = GLib.spawn_async( call, flags=GLib.SpawnFlags.DO_NOT_REAP_CHILD, standard_output=False, standard_error=True) self.fh_err = os.fdopen(fd_err, "r") GLib.child_watch_add(GLib.PRIORITY_DEFAULT, self.pid, self.video_complete) GLib.io_add_watch(self.fh_err, GLib.PRIORITY_DEFAULT, GLib.IOCondition.IN, self.video_error)
def __init__(self, port, obj, address = '', backlog = 5, tls = None, disconnect_cb = None): '''Listen on a port and accept connections. Set tls to a key+certificate file to use tls.''' self._disconnect_cb = disconnect_cb self.group = None self.obj = obj self.port = '' self.ipv6 = False self.socket = None self.tls = tls self.connections = set() if isinstance(port, str) and '/' in port: # Unix socket. # TLS is ignored for these sockets. self.tls = False self.socket = socket.socket(socket.AF_UNIX) self.socket.bind(port) self.port = port self.socket.listen(backlog) elif have_avahi and isinstance(port, str) and '|' in port: self._tls_init() self.socket = socket.socket() self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if address == '': self.socket6 = socket.socket(socket.AF_INET6) self.socket6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) info = port.split('|') self.port = port if len(info) > 2: self.socket.bind((address, lookup(info[2]))) self.socket.listen(backlog) if address == '': p = self.socket.getsockname()[1] self.socket6.bind(('::1', p)) self.socket6.listen(backlog) self.ipv6 = True bus = dbus.SystemBus() server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) self.group = dbus.Interface(bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()), avahi.DBUS_INTERFACE_ENTRY_GROUP) self.group.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), info[1], '_%s._tcp' % info[0], '', '', dbus.UInt16(self.socket.getsockname()[1]), '') self.group.Commit() else: self._tls_init() port = lookup(port) self.socket = socket.socket() self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((address, port)) self.socket.listen(backlog) if address == '': self.socket6 = socket.socket(socket.AF_INET6) self.socket6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket6.bind(('::1', port)) self.socket6.listen(backlog) self.ipv6 = True self.port = port fd = self.socket.fileno() GLib.io_add_watch(fd, GLib.IO_IN | GLib.IO_PRI | GLib.IO_HUP | GLib.IO_ERR, self._cb) if self.ipv6: fd = self.socket6.fileno() GLib.io_add_watch(fd, GLib.IO_IN | GLib.IO_PRI | GLib.IO_HUP | GLib.IO_ERR, self._cb)
def main(self): # watch socket recv = GLib.io_add_watch(self.fsock, GLib.IO_IN, self.method_recv) hup = GLib.io_add_watch(self.fsock, GLib.IO_HUP, self.method_hup) self.watchtag.append(recv) self.watchtag.append(hup) Gtk.main()
def run(self): ''' RUNS THE PROCESS ''' proc = subprocess.Popen(self.command, stdout=subprocess.PIPE) # SPAWNING GLib.io_add_watch( proc.stdout, # FILE DESCRIPTOR GLib.IO_IN, # CONDITION self.write_to_buffer) # CALLBACK
def pull_request(self): self.repo.state[0] = STATE_PULL_REQUEST_IN_PROGRESS cmd = "git fetch %s refs/pull/%s/head:%s && git checkout %s" % (self.repo.upstream_remote, self.new_branch_name, self.new_branch_name, self.new_branch_name) self.process = subprocess.Popen(cmd, cwd=self.repo.dir, stdout=subprocess.PIPE, stderr=STDOUT, shell=True, preexec_fn=os.setsid) GLib.io_add_watch(self.process.stdout, GLib.IO_IN, self.output_callback) self.new_branch_name = ""
def new_branch(self): self.repo.state[0] = STATE_NEW_BRANCH_IN_PROGRESS cmd = "git checkout -b %s" % (self.new_branch_name) self.process = subprocess.Popen(cmd, cwd=self.repo.dir, stdout=subprocess.PIPE, stderr=STDOUT, shell=True, preexec_fn=os.setsid) GLib.io_add_watch(self.process.stdout, GLib.IO_IN, self.output_callback) self.new_branch_name = ""
def rebase(self): self.repo.state[0] = STATE_REBASING cmd = "git pull --rebase %s %s" % (self.repo.upstream_remote, self.repo.upstream_branch) self.process = subprocess.Popen(cmd, cwd=self.repo.dir, stdout=subprocess.PIPE, stderr=STDOUT, shell=True, preexec_fn=os.setsid) GLib.io_add_watch(self.process.stdout, GLib.IO_IN, self.output_callback)
def __init__(self, f, callback): self.f = f self.callback = callback self.buf = "" fd = f.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) # Older, deperecated version GLib.io_add_watch(f.fileno(), GLib.IO_IN, self.data_in)
def _onEvent(self, source, cb_condition): info = self.sockDict[source] try: # check error if cb_condition & _flagError: raise _ConnException("Socket error, %s" % (GbsUtil.cbConditionToStr(cb_condition))) # HANDSHAKE_NONE if info.state == _HandShaker.HANDSHAKE_NONE: ctx = SSL.Context(SSL.SSLv3_METHOD) ctx.set_verify(SSL.VERIFY_PEER, _sslVerifyDummy) # ctx.set_mode(SSL.MODE_ENABLE_PARTIAL_WRITE) # fixme ctx.use_privatekey_file(self.privkeyFile) ctx.use_certificate_file(self.certFile) info.sslSock = SSL.Connection(ctx, source) info.sslSock.set_accept_state() info.state = _HandShaker.HANDSHAKE_WANT_WRITE # HANDSHAKE_WANT_READ & HANDSHAKE_WANT_WRITE if ((info.state == _HandShaker.HANDSHAKE_WANT_READ and cb_condition & GLib.IO_IN) or (info.state == _HandShaker.HANDSHAKE_WANT_WRITE and cb_condition & GLib.IO_OUT)): try: info.sslSock.do_handshake() info.state = _HandShaker.HANDSHAKE_COMPLETE except SSL.WantReadError: info.state = _HandShaker.HANDSHAKE_WANT_READ except SSL.WantWriteError: info.state = _HandShaker.HANDSHAKE_WANT_WRITE except SSL.Error as e: raise _ConnException("Handshake failed, %s" % (str(info.sslSock.getpeername())), e) # HANDSHAKE_COMPLETE if info.state == _HandShaker.HANDSHAKE_COMPLETE: # give socket to handShakeCompleteFunc self.handShakeCompleteFunc(source, self.sockDict[source].sslSock, self.sockDict[source].hostname, self.sockDict[source].port) del self.sockDict[source] return False except _ConnException as e: if not e.hasExcObj: logging.debug("_HandShaker._onEvent: %s, %s", e.message, str(info.sslSock.getpeername())) else: logging.debug("_HandShaker._onEvent: %s, %s, %s, %s", e.message, str(info.sslSock.getpeername()), e.excName, e.excMessage) self.handShakeErrorFunc(source, self.sockDict[source].hostname, self.sockDict[source].port) del self.sockDict[source] return False # register io watch callback again if info.state == _HandShaker.HANDSHAKE_WANT_READ: GLib.io_add_watch(source, GLib.IO_IN | _flagError, self._onEvent) elif info.state == _HandShaker.HANDSHAKE_WANT_WRITE: GLib.io_add_watch(source, GLib.IO_OUT | _flagError, self._onEvent) else: assert False return False
def addSocket(self, sock, hostname=None, port=None): info = _HandShakerConnInfo() info.state = _HandShaker.HANDSHAKE_NONE info.sslSock = None info.hostname = hostname info.port = port self.sockDict[sock] = info sock.setblocking(0) GLib.io_add_watch(sock, GLib.IO_IN | GLib.IO_OUT | _flagError, self._onEvent)
def build(self): self.repo.state[0] = STATE_BUILDING settings = Gio.Settings.new(SCHEMA) cmd = settings.get_string(KEY_BUILD) self.process = subprocess.Popen(cmd, shell=True, cwd=self.repo.dir, stdout = subprocess.PIPE, stderr = STDOUT, preexec_fn=os.setsid) GLib.io_add_watch(self.process.stdout, GLib.IO_IN, self.output_callback)
def main(): ''' Indeed: main program. ''' builder = Gtk.Builder() ui = os.path.dirname(os.path.abspath(__file__)) + "/update.ui" builder.add_from_file(ui) builder.connect_signals(Handler()) update_handler = UpdateHandler(builder) GLib.io_add_watch(0, GLib.IO_IN, update_handler.process_line) Gtk.main()
def attach_readfd(iochannel, context): # This does not work currently :-( # Also, things are mixed up a bit with iochannel vs. FDs apparently # as I am getting an int back in the handler # if isinstance(iochannel, int): # iochannel = GLib.IOChannel(iochannel) # source = GLib.io_create_watch(iochannel, GLib.IOCondition(GLib.IO_IN | GLib.IO_PRI)) # source.set_callback(_glib_signal_cb, context) # source.set_priority(GLib.PRIORITY_HIGH) # source.attach(context) GLib.io_add_watch(iochannel, GLib.IO_IN | GLib.IO_PRI, _glib_signal_cb, context)
def connect(self, hostname, port): # don't do repeat connect if (hostname, port) in self.sockSet: return self.sockSet.add((hostname, port)) # do operation #logging.debug("SnPeerClient.connect: Start, %s, %d", hostname, port) self.asyncns.getaddrinfo(hostname, None) self.asyncns.wait(False) GLib.io_add_watch(self.asyncns.get_fd(), GLib.IO_IN | _flagError, self._onResolveComplete, hostname, port)
def NewConnection(self, device, fd, fd_properties): print("new control connectin") self.conns[device] = HIDConnection(fd) def new_intr_conn(ssock, ip_type): sock, info = ssock.accept() print("interrput connection:", info) self.conns[device].register_intr_sock(sock) return False GLib.io_add_watch(self.sock, GLib.IO_IN, new_intr_conn)
def run(self): """ run main gtk thread """ try: GLib.timeout_add(self._heartbeat, self._update_plot) GLib.timeout_add(self._heartbeat, self._pad_make_step) GLib.io_add_watch(self.spectrum.conn_for_main, GLib.IO_IN | GLib.IO_PRI, self.spectrum.callback, args=(self.spectrum,)) if self.pad is not None: GLib.io_add_watch(self.pad.receiver, GLib.IO_IN | GLib.IO_PRI, self._on_pad_change, args=(self,)) Gtk.main() except KeyboardInterrupt: pass
def io_watch(source, cb_condition): ret = self.readData(source) # source.close() os.close(source) if ret: self.fifoFinal() Gtk.main_quit() else: # fd = open(self.fifo, 'r') fd = os.open(self.fifo, self.fifoMask, os.O_RDWR) GLib.io_add_watch(fd, GLib.IO_IN, io_watch) return False
def watch_debconf_fd(self, from_debconf, process_input): """Event loop interface to debconffilter. A frontend typically provides its own event loop. When a debconffiltered command is running, debconffilter must be given an opportunity to process input from that command as it arrives. This method will be called with from_debconf as a file descriptor reading from the filtered command and a process_input callback which should be called when input events are received.""" GLib.io_add_watch(from_debconf, GLib.IO_IN | GLib.IO_ERR | GLib.IO_HUP, self.watch_debconf_fd_helper, process_input)
def __init__(self, sock, callbacks, myid=0): self.sock = sock self.__reset() self.callbacks = callbacks self.myid = myid self.partid = 1 self.is_server = True sock.setblocking(0) GLib.io_add_watch(self.sock.fileno(), GLib.IO_IN, self.__data_in) GLib.io_add_watch(self.sock.fileno(), GLib.IO_ERR | GLib.IO_HUP, self.__error)
def _send(self, data): if not self._check_connection(): return self.write_buffer.append(data) if self.writing: return self.writing = True GLib.io_add_watch(self.sock.fileno(), GLib.IO_OUT, self.on_msg_write, priority=GLib.PRIORITY_LOW)
def connect_callback(self, response): if "CONNECT" in response: logging.info("Starting pppd") self.pppd = subprocess.Popen( ["/usr/sbin/pppd", "%s" % self.port, "115200", "defaultroute", "updetach", "usepeerdns"], bufsize=1, stdout=subprocess.PIPE) GLib.io_add_watch(self.pppd.stdout, GLib.IO_IN | GLib.IO_ERR | GLib.IO_HUP, self.on_pppd_stdout) GLib.timeout_add(1000, self.check_pppd) self.cleanup() else: self.cleanup() raise PPPException("Bad modem response %s, expected CONNECT" % response[0])
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) = GLib.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 GLib.child_watch_add( GLib.PRIORITY_DEFAULT, self.helper_pid, self._on_x2go_exit) # Add a watch on stdout channel = GLib.IOChannel.unix_new(self.helper_stdout) GLib.io_add_watch(channel, GLib.PRIORITY_DEFAULT, 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()