当前位置: 首页>>代码示例>>Python>>正文


Python GLib.idle_add方法代码示例

本文整理汇总了Python中gi.repository.GLib.idle_add方法的典型用法代码示例。如果您正苦于以下问题:Python GLib.idle_add方法的具体用法?Python GLib.idle_add怎么用?Python GLib.idle_add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在gi.repository.GLib的用法示例。


在下文中一共展示了GLib.idle_add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _connect

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def _connect(self, device):
        def cb_connect():
            try:
                bus = pydbus.SystemBus()
                proxy = bus.get(SERVICE_NAME, device.path)
                proxy.Connect()
            except KeyError:
                self._log.debug("The device has likely disappeared.", exc_info=True)
            except GLib.Error:
                self._log.debug("Connect() failed:", exc_info=True)
            else:
                self._log.info("Connection successful.")

            self.queued_connections -= 1

        if self.queued_connections == 0:
            print_device(device, "Connecting")
            GLib.idle_add(cb_connect)
            device.connected = True
            self.queued_connections += 1 
开发者ID:scipag,项目名称:btle-sniffer,代码行数:22,代码来源:sniffer.py

示例2: _async_call

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def _async_call(f, args, kwargs, on_done):
    def run(data):
        f, args, kwargs, on_done = data
        error = None
        result = None
        try:
            result = f(*args, **kwargs)
        except Exception as e:
            e.traceback = traceback.format_exc()
            error = 'Unhandled exception in asyn call:\n{}'.format(e.traceback)
        GLib.idle_add(lambda: on_done(result, error))

    data = f, args, kwargs, on_done
    thread = threading.Thread(target=run, args=(data,))
    thread.daemon = True
    thread.start() 
开发者ID:atareao,项目名称:daily-wallpaper,代码行数:18,代码来源:fsync.py

示例3: glib_idle_add_store_extend

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def glib_idle_add_store_extend(store, things, clear=False, wait=False):
	"""
	Extend a GTK store object (either :py:class:`Gtk.ListStore` or
	:py:class:`Gtk.TreeStore`) object using :py:func:`GLib.idle_add`. This
	function is suitable for use in non-main GUI threads for synchronizing data.

	:param store: The GTK storage object to add *things* to.
	:type store: :py:class:`Gtk.ListStore`, :py:class:`Gtk.TreeStore`
	:param tuple things: The array of things to add to *store*.
	:param bool clear: Whether or not to clear the storage object before adding *things* to it.
	:param bool wait: Whether or not to wait for the operation to complete before returning.
	:return: Regardless of the *wait* parameter, ``None`` is returned.
	:rtype: None
	"""
	if not isinstance(store, Gtk.ListStore):
		raise TypeError('store must be a Gtk.ListStore instance')
	idle_add = glib_idle_add_wait if wait else glib_idle_add_once
	idle_add(_store_extend, store, things, clear) 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:20,代码来源:gui_utilities.py

示例4: glib_idle_add_wait

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def glib_idle_add_wait(function, *args, **kwargs):
	"""
	Execute *function* in the main GTK loop using :py:func:`GLib.idle_add`
	and block until it has completed. This is useful for threads that need
	to update GUI data.

	:param function function: The function to call.
	:param args: The positional arguments to *function*.
	:param kwargs: The key word arguments to *function*.
	:return: The result of the function call.
	"""
	gsource_completed = threading.Event()
	results = []

	@functools.wraps(function)
	def wrapper():
		results.append(function(*args, **kwargs))
		gsource_completed.set()
		return False
	GLib.idle_add(wrapper)
	gsource_completed.wait()
	return results.pop() 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:24,代码来源:gui_utilities.py

示例5: run_on_master_thread_when_idle

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def run_on_master_thread_when_idle(func, **func_args):
    '''
    This function allows other threads (runing the API) to call a function
    on the master thread (running GStreamer) at a moment when it is idle.
    '''
    def function_runner(args):
        if args['func'] is None:
            raise RuntimeError('Missing function to run on master thread (within run function)!')

        try:
            f = args['func']
            func_args = args['func_args']
            f(**func_args)
        except Exception as e:
            print('------------ UNCAUGHT EXCEPTION ON MASTER THREAD: %s ------------' % e, file=sys.stderr)
            print(traceback.format_exc(), file=sys.stderr)

        return False

    if func is None:
        raise RuntimeError('Missing function to run on master thread!')
    GLib.idle_add(function_runner, {'func': func, 'func_args': func_args}) 
开发者ID:bbc,项目名称:brave,代码行数:24,代码来源:helpers.py

示例6: __init__

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def __init__(self, app):
    self.app    = app
    self.stack  = app.channels_stack
    self.filter = None

    self.channels = Gtk.Builder()
    self.channels.add_from_file(relative_path('ui/channels.ui'))
    self.channels.connect_signals(self)

    self.channels_box = self.channels.get_object('box_channels')
    self.stack.add_named(self.channels_box, 'channels_container')

    self.channels_filters = self.channels.get_object('list_box_channels_filters')
    self.channels_list    = self.channels.get_object('flow_box_channels_list')
    self.channels_list.set_filter_func(self.on_channels_list_row_changed)

    GLib.idle_add(self.do_initial_setup) 
开发者ID:jonian,项目名称:kickoff-player,代码行数:19,代码来源:channel.py

示例7: main

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def main():
    loop = asyncio.get_event_loop()
    glib_loop = GLib.MainLoop()

    try:
        panctl = PanCtl()
    except GLib.Error as e:
        print(f"Error, {e}")
        sys.exit(-1)

    fut = loop.run_in_executor(None, glib_loop.run)

    try:
        loop.run_until_complete(panctl.loop())
    except KeyboardInterrupt:
        pass

    GLib.idle_add(glib_loop.quit)
    loop.run_until_complete(fut) 
开发者ID:matrix-org,项目名称:pantalaimon,代码行数:21,代码来源:panctl.py

示例8: execute

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def execute(self, inputs, outputs, gvm):
    self.logger.debug("Delete state")
    state_id = inputs["generated_state_id"]
    # the target state is the hierarchy state, which holds this library state as child state
    target_state = self.parent.parent
    
    call_gui_callback(target_state.remove_state, state_id)
    # do not call this with idle_add, otherwise the oberserver will be triggered asynchronously
    # i.e. the before notification will be handled after the whole operation already happend
    #GLib.idle_add(target_state.remove_state, state_id)
    
    while state_id in target_state.states.keys():
        time.sleep(0.1)
    
    wait_for_gui()
    
    #call_gui_callback(wait_for_gui)
    
    #time.sleep(2.0)
    return 0 
开发者ID:DLR-RM,项目名称:RAFCON,代码行数:22,代码来源:script.py

示例9: print_message

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def print_message(self, message, log_level):
        with self._lock:
            if log_level <= log.logging.VERBOSE and self._enables.get('VERBOSE', False):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "debug",
                              priority=GLib.PRIORITY_LOW)
            if log.logging.VERBOSE < log_level <= log.logging.DEBUG and self._enables.get('DEBUG', True):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "debug",
                              priority=self.logging_priority)
            elif log.logging.DEBUG < log_level <= log.logging.INFO and self._enables.get('INFO', True):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "info",
                              priority=self.logging_priority)
            elif log.logging.INFO < log_level <= log.logging.WARNING and self._enables.get('WARNING', True):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "warning",
                              priority=self.logging_priority)
            elif log.logging.WARNING < log_level and self._enables.get('ERROR', True):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "error",
                              priority=self.logging_priority) 
开发者ID:DLR-RM,项目名称:RAFCON,代码行数:19,代码来源:logging_console.py

示例10: register_signal_handlers

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def register_signal_handlers(callback):
    # When using plain signal.signal to install a signal handler, the GUI will not shutdown until it receives the
    # focus again. The following logic (inspired from https://stackoverflow.com/a/26457317) fixes this
    def install_glib_handler(sig):
        unix_signal_add = None

        if hasattr(GLib, "unix_signal_add"):
            unix_signal_add = GLib.unix_signal_add
        elif hasattr(GLib, "unix_signal_add_full"):
            unix_signal_add = GLib.unix_signal_add_full

        if unix_signal_add:
            unix_signal_add(GLib.PRIORITY_HIGH, sig, callback, sig)

    def idle_handler(*args):
        GLib.idle_add(callback, *args, priority=GLib.PRIORITY_HIGH)

    for signal_code in [signal.SIGHUP, signal.SIGINT, signal.SIGTERM]:
        signal.signal(signal_code, idle_handler)
        GLib.idle_add(install_glib_handler, signal_code, priority=GLib.PRIORITY_HIGH) 
开发者ID:DLR-RM,项目名称:RAFCON,代码行数:22,代码来源:start.py

示例11: wait_for_update

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def wait_for_update(self, trigger_update=False):
        """Update canvas and handle all events in the gtk queue

        :param bool trigger_update: Whether to call update_now() or not
        """
        if trigger_update:
            self.update_now()

        from gi.repository import Gtk
        from gi.repository import GLib
        from threading import Event
        event = Event()

        # Handle all events from gaphas, but not from gtkmvc3
        # Make use of the priority, which is higher for gaphas then for gtkmvc3
        def priority_handled(event):
            event.set()
        priority = (GLib.PRIORITY_HIGH_IDLE + GLib.PRIORITY_DEFAULT_IDLE) / 2
        # idle_add is necessary here, as we do not want to block the user from interacting with the GUI
        # while gaphas is redrawing
        GLib.idle_add(priority_handled, event, priority=priority)
        while not event.is_set():
            Gtk.main_iteration() 
开发者ID:DLR-RM,项目名称:RAFCON,代码行数:25,代码来源:canvas.py

示例12: _load_thread

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def _load_thread(self, loader, path):
        # The try ... except wrapper and the _faulty_image attribute are used to
        # catch weird images that break GdkPixbufLoader but work otherwise
        # See https://github.com/karlch/vimiv/issues/49 for more information
        try:
            self._faulty_image = True
            with open(path, "rb") as f:
                image_bytes = f.read()
                loader.write(image_bytes)
            self._faulty_image = False
            loader.close()
        except GLib.GError:
            self._pixbuf_original = GdkPixbuf.Pixbuf.new_from_file(path)
            self._faulty_image = False
            self._set_image_pixbuf()
            GLib.idle_add(self._update) 
开发者ID:karlch,项目名称:vimiv,代码行数:18,代码来源:image.py

示例13: _thread_for_external

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def _thread_for_external(self, cmd, p, from_pipe):
        """Start a new thread for external commands.

        Args:
            cmd: The command to run.
            directory: Directory which is affected by command.
        """
        # Get output and error and run the command
        out, err = p.communicate()
        if p.returncode:
            message = "Command exited with status " + str(p.returncode) + "\n"
            message += err.decode()
            GLib.idle_add(self._app["statusbar"].message, message, "error")
        else:
            # Run pipe if we have output
            if from_pipe:
                GLib.idle_add(self._run_pipe, out)
            # We do not know what might have changed concerning paths
            else:
                GLib.idle_add(self._app.emit, "paths-changed", self)
        self.running_processes.pop() 
开发者ID:karlch,项目名称:vimiv,代码行数:23,代码来源:commandline.py

示例14: glib_idle_add_once

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def glib_idle_add_once(function, *args, **kwargs):
	"""
	Execute *function* in the main GTK loop using :py:func:`GLib.idle_add`
	one time. This is useful for threads that need to update GUI data.

	:param function function: The function to call.
	:param args: The positional arguments to *function*.
	:param kwargs: The key word arguments to *function*.
	:return: The result of the function call.
	"""
	@functools.wraps(function)
	def wrapper():
		function(*args, **kwargs)
		return False
	return GLib.idle_add(wrapper) 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:17,代码来源:gui_utilities.py

示例15: _set_text_view

# 需要导入模块: from gi.repository import GLib [as 别名]
# 或者: from gi.repository.GLib import idle_add [as 别名]
def _set_text_view(self, string_to_set):
		GLib.idle_add(self.text_buffer.set_text, string_to_set + '\n') 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:4,代码来源:campaign_import.py


注:本文中的gi.repository.GLib.idle_add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。