|
# simple python-dbus service that exposes 1 method called hello()
import gtk import dbus import dbus.service import dbus.glib class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('org.frankhale.helloservice', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/org/frankhale/helloservice') @dbus.service.method('org.frankhale.helloservice') def hello(self): return "Hello,World!" myservice = MyDBUSService() gtk.main() ####################### # consumeservice.py # consumes a method in a service on the dbus import dbus bus = dbus.SessionBus() helloservice = bus.get_object('org.frankhale.helloservice', '/org/frankhale/helloservice') hello = helloservice.get_dbus_method('hello', 'org.frankhale.helloservice') print hello() Communicating with our application using python and dbus | FlaPer87
www.flaper87.org/2008/06/04/communicating-with-our... Communicating with our application using python and dbusSubmitted by flaper87 on Wed, 06/04/2008 - 10:32. Hi!! I've been programming the httpServer and the dbusServer for mouseTrap and I wanted to share how simple is communicate with our applications using dbus and its python bindings. The piece of code we are interested in is this: import dbus
import gobject
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
main_loop = DBusGMainLoop()
bus = dbus.SessionBus(mainloop=main_loop)
DBUS_NAME = "org.myApp"
DBUS_PATH = "/org/myApp"
class myAppdBus(dbus.service.Object):
"""
Our dbus Class
"""
def __init__( self ):
"""
Starting the dbus service.
"""
global bus
bus_name = dbus.service.BusName(DBUS_NAME, bus=bus)
dbus.service.Object.__init__(self, bus_name, DBUS_PATH)
@dbus.service.method(DBUS_NAME)
def do( self ):
"""
Function to execute using dbus service
"""
print "do function has been called using dbus service"
class myApp:
def __init__(self):
self.loop = gobject.MainLoop()
d = myAppdBus()
def start(self):
self.loop.run()
if __name__ == '__main__':
app = myApp()
app.start()
It is a simple script with 2 classes. The main class called myApp will call the dbus class (myAppdBus) and will start the applications main loop. The second class (myAppdBus) is the dbus class, it starts the service and register the methods that can be called using dbus. The script can be executed like this (in my case the name of the script is dbus_script.py):
After running the script it is possible to execute the do function like this:
This last command will show us the information related to the call we just executed. The output is something like: flaper87@r4-p17:~$ dbus-send --reply-timeout=30000 --print-reply --dest=org.myApp /org/myApp org.myApp.do method return sender=:1.6 -> dest=:1.7 reply_serial=2 Ass you can the classes are really simple and show an easy way to communicate with our applications using dbus. There are a lot of options a tweaks that can be implemented so it's all in you hands now. Rough notes: Python and D-Bus
At work I had to figure out how to use D-Bus from Python. GNOME documentation generally sucks, so I'm posting the following notes in case they provide useful to someone (maybe me in six months).
D-Bus is a
system-wide message bus used by the GNOME desktop. Python D-Bus
bindings are available; in Ubuntu, they're in the There are two buses, one that's system-wide and one that's tied to your desktop session. The system-wide bus lets you talk to unique daemons, such as the Avahi server that I'm interested in, and the session bus talks to your current panel, window manager, or whatever. To start off, you import the modules and get an object for the message bus you want: import avahi, dbus, dbus.glib bus = dbus.SystemBus() Once you have the bus, you need to find an object to talk to; this is done by requesting a particular application and an object path that's a unique identifier within that application. (One application can contain many different objects; consider a window manager that has a number of windows open.) Applications are identified by Java package-style reversed domain names, like "org.freedesktop.Avahi". Avahi happens to contain constants for these identifiers, but you can also just specify them as literals: raw_server = bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER)
# = ('org.freedesktop.Avahi', '/')
An object can support any number of different interfaces. Before calling any methods, you need to specify which interface you want to use. They're also identified by reversed domains: server = dbus.Interface(raw_server, avahi.DBUS_INTERFACE_SERVER) # = "org.freedesktop.Avahi.Server" The Avahi developers don't actually document their API anywhere.
You have to read some XML files that are in
<method name="ResolveService">
<arg name="interface" type="i" direction="in"/>
<arg name="protocol" type="i" direction="in"/>
<arg name="name" type="s" direction="in"/>
<arg name="type" type="s" direction="in"/>
<arg name="domain" type="s" direction="in"/>
<arg name="aprotocol" type="i" direction="in"/>
<arg name="flags" type="u" direction="in"/>
<arg name="interface" type="i" direction="out"/>
<arg name="protocol" type="i" direction="out"/>
<arg name="name" type="s" direction="out"/>
<arg name="type" type="s" direction="out"/>
<arg name="domain" type="s" direction="out"/>
<arg name="host" type="s" direction="out"/>
<arg name="aprotocol" type="i" direction="out"/>
<arg name="address" type="s" direction="out"/>
<arg name="port" type="q" direction="out"/>
<arg name="txt" type="aay" direction="out"/>
<arg name="flags" type="u" direction="out"/>
</method>
Annoyingly, the XML doesn't contain any comments describing the
semantics of the methods, so you have to hope that the method
names are understandable. I had to figure out legal values for some parameters by looking at Avahi example code. Calling the above output = server.ResolveService(interface, protocol, name, type,
domain, avahi.PROTO_UNSPEC, dbus.UInt32(0))
(interface2, protocol2, name2, type2, domain2, ...) = output
Interfaces can also support signals. The following example creates
a new # Call method to create new browser, and get back an object path for it.
obj_path = server.ServiceBrowserNew(interface, protocol, '_durus._tcp',
domain, dbus.UInt32(0))
# Create browser interface for the new object
browser = dbus.Interface(bus.get_object(avahi.DBUS_NAME, obj_path),
avahi.DBUS_INTERFACE_SERVICE_BROWSER)
# Connect signals for browser -- they'll be called as new ZeroConf
# services are seen.
browser.connect_to_signal('ItemNew', new)
browser.connect_to_signal('AllForNow', all_for_now)
Here's a small service written in Python: import avahi, dbus, dbus.glib, dbus.service
import gobject
class Server (dbus.service.Object):
@dbus.service.method(dbus_interface='ca.amk.Interface',
in_signature='', out_signature='si')
def get_result (self):
return ('hello', 42)
bus = dbus.SessionBus()
name = dbus.service.BusName('ca.amk.Server', bus=bus)
obj = Server(name, '/')
loop = gobject.MainLoop()
print 'Listening'
loop.run()
And here's the corresponding client: import dbus, dbus.glib
bus = dbus.SessionBus()
server = dbus.Interface(bus.get_object('ca.amk.Server', '/'),
'ca.amk.Interface')
print server.get_result()
The example uses the session bus because an ordinary user can't run services on the system bus; you could spoof system daemons if that was allowed. programming: Ask Reddit: What's the most beautiful piece of publically available source code you
programming.reddit.com/info/26dyh/comments Julian Noble's finite state machines in Forth: http://dec.bournemouth.ac.uk/forth/jfar/vol7/paper1/paper.html programming: Ask Reddit: What's the most beautiful piece of publically available source code you
programming.reddit.com/info/26dyh/comments Lua's VM is powerful and fast, but small enough to comprehend in one sitting and is nothing but extremely clean, readable ANSI C. For what it's worth, I *did* convince my boss; I've used Chicken to write a set of Web applications to supplement one of our campus systems. None of the apps was supposed to last more than a semester -- we expected that the primary system itself would grow the same features during that time -- so they were somewhat willing to let me take a couple risks. But that was two semesters ago, and the Chicken apps are still in business. They've only served about 2 million requests so far (about 10,000 per day right now), which is far from huge, but they can take a heavier load. Lord knows I've had a couple problems with them (mostly self-inflicted ones), but overall it's been a tremendous win. Some of the things I would have used in my elevator pitch for Chicken (keeping in mind that Web apps are my thing): - running an application in a REPL (no compilation step; redefine anything you want, any time) is the rapidest development environment you can get, bar none. - It's also a great maintenance environment; almost all bugs can be corrected live, without restarting a single process. - works with all major databases (don't use that Fawcett guy's Oracle driver, though, it's a piece of crap); works great without them, too. - can use third-party libraries written in C, Java, Python. - You can compile the stuff that needs to run faster. Web apps don't tend to have too many hotspots, though. - Chicken and Scheme are relatively easy to learn, and there are plenty of resources available. - works great in a Unix environment, where forking processes is cheap: you can write small, fast programs that are suitable for Unix-style design (forks, pipes, etc.). Try *that* with Java. This is a good approach for shared-nothing, highly-scalable apps. Not that I wrote mine that way... ;-) - What the community lacks in size, it makes up for in brain-power and supportiveness. Everyone here knows that stuff, of course. ;-) Premature architecture can be more dangerous than
none at all, as unproved architectural hypotheses turn into straightjackets that
discourage evolution and experimentation.
PHP—paraphrasing someone else—rewards lazy thinking. Some things, like "magic quotes," reflect the true mindset of the PHP community. Now, of course, this dead horse has been beaten to a featureless blob in the PHP world (I think?), but it bears repeating: rather than focus on educating amateur programmers on learning to separate data and teaching them SQL syntax (no, it is not correct to simply splice arbitrary data into your SQL query), and rather than looking for an elegant technological solution to SQL injection (e.g. prepared statements), they replaced every goddamned apostrophe on input with You cannot write correct PHP software (portable to different server configurations) that takes user input subject to magic-quotes (e.g. from GET/POST/cookie data) without working-around magic-quotes if they're enabled. There is no statement you can use to the effect of "hi, I know what I'm doing, please disable magic quotes for this script." Rather, you have to check whether magic quotes are enabled and un-munge their "encoding" when you read input data. Elegant! Speaking of data separation and encoding, you'd think a "web programming language" would have excellent support for the W3C DOM. I haven't done much web programming that involves DOM for server-side document generation, but it's certainly an interesting idea, and ought to reduce XSS problems. Sadly, PHP's documentation on DOM is greatly incomplete (as of about one year ago). PHP tends to be documented imprecisely, because there's only one implementation of the language. For instance, it's really, really hard figuring out what's going on with the reference semantics and the But that requires having concepts like object identity down. For instance, in Javascript, when There's other minutiae that really get under my skin with PHP. This is my therapy: You can nest function definitions in PHP, but these nested functions are semantically equivalent to if you had simply defined the functions side-by-side. Why is this allowed in the first place? This is confusing when you come from languages with lexical scoping, where it does make sense to create and combine functions in a limited scope. PHP tried to support the lambda expression of higher-order programming by implementing create_function(). This function takes an argument list and a function body as input, and returns a new function. Reasonable enough, right? Well...
The syntax alone of trying to do anything with PHP's scoping is also overly simplistic: you have "global" variables, and you have "local" variables. That's it. The local variables of some function are not visible anywhere else—of course. This is highly problematic if you'd like to use * Edit: magic-quote run-time pain. I have somewhat mixed feelings about closures: they are pretty complicated.
But they're an instance of what I think of as the Black Hole Theory of Design.
I have a really strong memory from years ago of Guy Steele saying roughly "Lisp is a
Black Hole: if you try to design something that's not Lisp, but like Lisp, you'll
find that the gravitational forces on the design will suck it into the Black Hole, and it
will become Lisp". [Guy doesn't actually remember making this remark, but he
does say it sounds like the kind of flip comment he would make; I could also be totally
mis-remembering who said it, but I haven't found any quote like it through Google].
escm is a filter program which takes a text with embedded Scheme exressions, copies it to the output with evaluating the Scheme expressions. You can use the power of Scheme to preprocess various text files, including CGI scripts. It's not true that CL doesn't have continuations at all. First some terminology: - There are one-shot and multi-shot continuations. The difference is that a one-shot continuations is only called once while a multi-shot continuation is called several times. - There are escaping and non-escaping continuations. If you grab a continuation, for example with call/cc, and during the execution of that call/cc invoke the continuation, this is called an escaping continuation because the continuation escapes from the current control flow. If the execution of that call/cc is already over (either normally or via the invocation of that continuation), and you call that continuation (possibly a second time), then this is called a non-escaping continuation because you are actually returning to a point of execution that was already "escaped." Scheme supports one-shot and multi-shot escaping and non-escaping continuations. Common Lisp provides the pairs catch/throw and block/return-from which are one-shot escaping continuations. Common Lisp doesn't support multi-shot or non-escaping continuations. It seems to me that in a lot of cases, Scheme's continuations are only invoked once if at all and are invoked during the extent of the respective call/cc, so are effectively used as one-shot escaping continuations. In those cases it is relatively straightforward to translate the code to Common Lisp, just replace them with the appropriate constructs (typically block/return-from). Only if they are used as multi-shot and/or as non-escaping continuations, then you need to worry more about them. For example, when continuations are used to simulate threads, or when they are used as building blocks for web applications, then they are used as non-escaping continuations.
A long-time Lisp programmer like me would do something like that: (define (flatten l) (cond ((null? l) ()) ((list? l) (append (flatten (car l)) (flatten (cdr l)))) (else (list l)) ) ) which means in short: - if the list is empty, just return the empty list - if the list is a real list, flatten its car, flatten its cdr and append the resulting lists - if the list is not a list, return the "atom" in a list (so "(flatten 'a)" will be "(a)" - don't know if this is what you want...) It should work (but I haven't tested it...). But maybe it isn't in the DSSSL way of thinking... I do that sort of scripting all the time, except I write it in Scheme. Example is recursing down directories generating svn logs (svn log doesn't recurse by itself). In PLT Scheme fold-files [To use: (require (lib "file.ss"))] is your friend.
Take a look at this page http://www.pscience5.net/CFPartition.htm, which *will* make your CF bootable, and install DOS and a partition manager. Its cool getting an amiga to boot from CF card I have done this many times The Joel Test: 12 Steps to Better Code - Joel on Software
www.joelonsoftware.com/articles/fog0000000043.html
Reading Code is Like Reading the Talmud - Joel on Software
www.joelonsoftware.com/articles/fog0000000053.html Talmud-reading tactics are, I think, also useful for code-reading: Long story short, surf the web from http://www.google.com/xhtml or www.google.com/gwt/n to get a proxied & simplified version of any page you want to visit. Haskell indenting
|