python/ruby question..

Matimus mccredie at gmail.com
Thu Jun 19 19:23:57 EDT 2008


On Jun 19, 4:00 pm, Matimus <mccre... at gmail.com> wrote:
> On Jun 18, 8:33 pm, "bruce" <bedoug... at earthlink.net> wrote:
>
>
>
> > hi...
>
> > can someone point me to where/how i would go about calling a ruby app from a
> > python app, and having the python app being able to get a returned value
> > from the ruby script.
>
> > something like
>
> > test.py
> >  a = os.exec(testruby.rb)
>
> > testruby.py
> >  foo = 9
> >  return foo
>
> > i know this doesn't work... but i've been searching for hours on this with
> > no luck.... (and yeah, i'm relatively new to both ruby/python!!)
>
> > thanks
>
> Both Ruby and Python appear to support XMLRPC. I haven't used XMLRPC
> in Ruby, but in general you create a server and expose some functions.
> On the client end (Python) you would do something like this (assuming
> you are serving on port 8050):
>
> import xmlrpclib
>
> rubyserver = xmlrpclib.Server("http://localhost:8050")
> x = rubyserver.foo(1,2,3)
>
> where 'foo' is a function served by the ruby server and x is its
> return value.
>
> some links:
>
> http://www.ruby-doc.org/stdlib/libdoc/xmlrpc/rdoc/index.html
>
> Good python server and client examples on this page:
>
> http://docs.python.org/lib/simple-xmlrpc-servers.html
>
> I can't be of much help for ruby, and that link doesn't seem to help
> much other than to say 1. it exists and 2. its easy.
>
> Matt

Here is a more complete example.

The ruby server code:

require "xmlrpc/server"

s = XMLRPC::Server.new(8080)

s.add_handler("add") do |a,b|
  a + b
end

s.add_handler("div") do |a,b|
  if b == 0
    raise XMLRPC::FaultException.new(1, "division by zero")
  else
    a / b
  end
end

s.set_default_handler do |name, *args|
  raise XMLRPC::FaultException.new(-99, "Method #{name} missing" +
                                   " or wrong number of parameters!")
end

s.serve

I put the above code into a file xmlrpctest.rb and ran it at the
command line. Then I opened the python interpreter in a separate
window and did this:

>>> s = xmlrpclib.Server("http://localhost:8080")
>>> s.div(100,2.0)
50.0
>>> s.add(100000, 2)
100002
>>>

In the long run you may still want to use the subprocess module to
launch the ruby xmlrpc server, but once you do that communicating
between the two processes should be pretty simple.

Matt



More information about the Python-list mailing list