本文整理匯總了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
示例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()
示例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)
示例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()
示例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})
示例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)
示例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)
示例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
示例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)
示例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)
示例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()
示例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)
示例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()
示例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)
示例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')