Importing your Python modules into Ruby

January 8, 2012 - Words by Matej Artač

January 8, 2012
Words by Matej Artač

I am considering using Cucumber for testing a project we have in Python. Since Cucumber uses Ruby for doing the actual work, the question is how to bridge with Python.

There are, of course, several options, like calling the Python code as a shell script from Ruby. Or maybe XML-RPC? To me, however, the most convenient way would be to do at least basic calls to Python methods from Ruby.

For this, RubyPython comes to the rescue. Building this bridge is not all that straightforward, though.

To install it, it is easiest to use

$ gem install rubypython

The command compiles the native extensions, so make sure that ruby-dev package is installed as well. This works with the Ruby 1.9.1 in Ubuntu. Just have

$ sudo apt-get install ruby1.9.1 uby1.9.1-dev

then call

$ gem1.9.1 install rubypython

A box without the dev package will complain with mkmf LoadError.

The RubyPython gives a good enough overvierw, and there’s some more info here. The examples show how to import and use the modules that ship or are installed with Python. I encountered a problem, however, that RubyPython could not find the modules that I created and put in the same directory as my Ruby code. Looking at the Python documentation for modules gave me a clue that I’d need to tell the Python VM running embedded in Ruby that it should look for modules in other locations as well. So before calling irb or my Ruby code, I did this in the bash shell:

$ export PYTHONPATH=".:/usr/local/lib/python2.7"

and that did the trick, my Ruby code is loading my Python modules and invoking their methods. Curiously enough, though, setting the ENV[‘PYTHONPATH’] from within Ruby didn’t have the right effect.


Social media

Keep up with what we do on our social media.