def inputhook(context):
"""
When the eventloop of prompt-toolkit is idle, call this inputhook.
This will run the GTK main loop until the file descriptor
`context.fileno()` becomes ready.
:param context: An `InputHookContext` instance.
"""
def _main_quit(*a, **kw):
gtk.main_quit()
return False
gobject.io_add_watch(context.fileno(), gobject.IO_IN, _main_quit)
gtk.main()
python类main()的实例源码
def main(argv):
global commands
# now we need to find out if one of the commands are in the
# argv list, and if so split the list at the point to
# separate the argv list at that point
cut = None
for i in range(len(argv)):
if argv[i] in commands or argv[i] in aliases:
cut = i
break
if cut == None:
usage(argv)
os._exit(0)
return
# lol no options for now
globaloptionparser = optparse.OptionParser()
globaloptionparser.parse_args(argv[0:i])
# now dispatch and run
result = None
if argv[i] in commands:
result = commands[argv[i]](argv[i+1:])
elif argv[i] in aliases:
result = aliases[argv[i]](argv[i+1:])
# flush, in case output is rerouted to a file.
console_flush()
# done
return result
def main(self):
thread = Thread(target=uBitPoller)
thread.daemon = True
thread.start()
thread = Thread(target=pipePoller, args=(self,))
thread.daemon = True
thread.start()
thread = Thread(target=updateTitle)
thread.daemon = True
thread.start()
gtk.main()
def copy_url(url):
"""Copy the url into the clipboard."""
# try windows first
try:
import win32clipboard
except ImportError:
# then give pbcopy a try. do that before gtk because
# gtk might be installed on os x but nobody is interested
# in the X11 clipboard there.
from subprocess import Popen, PIPE
try:
client = Popen(['pbcopy'], stdin=PIPE)
except OSError:
try:
import pygtk
pygtk.require('2.0')
import gtk
import gobject
except ImportError:
return
gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD).set_text(url)
gobject.idle_add(gtk.main_quit)
gtk.main()
else:
client.stdin.write(url)
client.stdin.close()
client.wait()
else:
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(url)
win32clipboard.CloseClipboard()
def main(self, task=None,checkpoint=None):
self.zarj_comm.start()
self.window.show_all()
self.idle_id = gobject.idle_add(self.gtk_idle_cb)
if task is not None and checkpoint is not None:
msg = ZarjStartCommand(task, checkpoint, True)
self.zarj_comm.push_message(msg)
gtk.main()
self.zarj_comm.stop()
def draw_lidar(self):
if self.lidar_msg is not None:
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 512, 20)
a = pixbuf.get_pixels_array()
camera_increment = (2 * 1.3962) / 512
offset = (len(self.lidar_msg.ranges) - (2 * 512)) / 2
scale = 255.0 / (self.lidar_msg.range_max - self.lidar_msg.range_min)
for x in range(512):
angle = -1.3962 + (camera_increment * x)
distance = self.lidar_distance_for_angle(angle)
self.lidar_depth[x] = round(distance, 2)
if distance <= self.lidar_msg.range_min:
scaled = 0
elif distance >= self.lidar_msg.range_max:
scaled = 255
else:
scaled = distance * scale
color = [ 0, 255 - int(scaled), 0 ]
for y in range(20):
a[y, x] = color
if round(math.degrees(angle), 0) % 30 == 0:
a[0, x] = [255, 0, 0]
a[19, x] = [255, 0, 0]
if angle == 0.0:
a[0, x] = [255, 0, 0]
a[1, x] = [255, 0, 0]
a[18, x] = [255, 0, 0]
a[19, x] = [255, 0, 0]
pixmap, mask = pixbuf.render_pixmap_and_mask()
self.lidar.set_from_pixmap(pixmap, mask)
# Ideally, we process in the main thread context, hopefully
# preventing bugs...
def run( Widget, w, h, speed ):
window = gtk.Window( )
window.connect( "delete-event", gtk.main_quit )
widget = Widget( w, h, speed )
widget.show( )
window.add( widget )
window.present( )
gtk.main( )
def main():
gtk.main()
return 0
def main(self):
gtk.main()
def run(Widget):
window = gtk.Window()
window.connect("delete-event", gtk.main_quit)
widget = Widget()
widget.show()
window.add(widget)
window.present()
gtk.main()
def show(self):
"""Opens a GTK window and puts the heatmap in it. Intelligent enough to work with the GUI as well."""
window_only = 1 #What needs to be destroyed when the window is destroyed?
if HMAP_ENABLED and DISPLAY_ENABLED:
def destroy():
if window_only:
window.destroy()
else:
gtk.main_quit()
gtk.gdk.threads_enter()
window = gtk.Window()
window.set_title("Showing heatmap...")
window.set_border_width(10)
window.set_resizable(False)
window.connect("delete_event", lambda w, e: destroy())
backbone = gtk.HBox(True)
image = gtk.Image()
image.set_from_pixbuf(self._image_to_pixbuf(self.im))
backbone.pack_start(image)
window.add(backbone)
window.show_all()
gtk.gdk.threads_leave()
if gtk.main_level() == 0:
window_only = 0
gtk.main()
else:
raise "HmapError", "Error loading modules or unable to display"
def __init__(self, useGtk=True):
self.context = gobject.main_context_default()
self.loop = gobject.MainLoop()
posixbase.PosixReactorBase.__init__(self)
# pre 2.3.91 the glib iteration and mainloop functions didn't release
# global interpreter lock, thus breaking thread and signal support.
if (hasattr(gobject, "pygtk_version") and gobject.pygtk_version >= (2, 3, 91)
and not useGtk):
self.__pending = self.context.pending
self.__iteration = self.context.iteration
self.__crash = self.loop.quit
self.__run = self.loop.run
else:
import gtk
self.__pending = gtk.events_pending
self.__iteration = gtk.main_iteration
self.__crash = _our_mainquit
self.__run = gtk.main
# The input_add function in pygtk1 checks for objects with a
# 'fileno' method and, if present, uses the result of that method
# as the input source. The pygtk2 input_add does not do this. The
# function below replicates the pygtk1 functionality.
# In addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and
# g_io_add_watch() takes different condition bitfields than
# gtk_input_add(). We use g_io_add_watch() here in case pygtk fixes this
# bug.
def _doReadOrWrite(self, source, condition, faildict={
error.ConnectionDone: failure.Failure(error.ConnectionDone()),
error.ConnectionLost: failure.Failure(error.ConnectionLost()),
}):
why = None
didRead = None
if condition & POLL_DISCONNECTED and \
not (condition & gobject.IO_IN):
why = main.CONNECTION_LOST
else:
try:
if condition & gobject.IO_IN:
why = source.doRead()
didRead = source.doRead
if not why and condition & gobject.IO_OUT:
# if doRead caused connectionLost, don't call doWrite
# if doRead is doWrite, don't call it again.
if not source.disconnected and source.doWrite != didRead:
why = source.doWrite()
didRead = source.doWrite # if failed it was in write
except:
why = sys.exc_info()[1]
log.msg('Error In %s' % source)
log.deferr()
if why:
self._disconnectSelectable(source, why, didRead == source.doRead)
def run(self, installSignalHandlers=1):
import gtk
self.startRunning(installSignalHandlers=installSignalHandlers)
self.simulate()
# mainloop is deprecated in newer versions
if hasattr(gtk, 'main'):
gtk.main()
else:
gtk.mainloop()
def install(useGtk=True):
"""Configure the twisted mainloop to be run inside the gtk mainloop.
@param useGtk: should glib rather than GTK+ event loop be
used (this will be slightly faster but does not support GUI).
"""
reactor = Gtk2Reactor(useGtk)
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor
def portableInstall(useGtk=True):
"""Configure the twisted mainloop to be run inside the gtk mainloop.
"""
reactor = PortableGtkReactor()
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor
def run(self, installSignalHandlers=1):
self.startRunning(installSignalHandlers=installSignalHandlers)
self.simulate()
gtk.main()
def install():
"""Configure the twisted mainloop to be run inside the gtk mainloop.
"""
reactor = GladeReactor()
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor
def main(self):
"""Enters the main loop."""
gtk.main()
def main():
#
# In order to uniquely identify the service, pass in an
# alias name and socket id on the command line
global g_service_alias
global g_socket_id
if len(sys.argv) == 3:
g_service_alias = sys.argv[1]
g_socket_id = int(sys.argv[2])
elif len(sys.argv) > 2:
print "Usage: lcd_service.py (service_alias_name socket_id)"
sys.exit(2)
else:
# defaults
g_service_alias = "LCD1"
g_socket_id = 18861
print "Using service alias:", g_service_alias, " and socket id", g_socket_id
# Initialize threads
gtk.threads_init()
start_new_display()
start_new_service()
# gtk multithreaded stuff
gtk.threads_enter()
gtk.main()
gtk.threads_leave()