Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Python from Ruby

Tags:

python

ruby

I have a compiled Python library and API docs that I would like to use from Ruby.

Is it possible to load a Python library, instantiate a class defined in it and call methods on that object from Ruby?

like image 766
Bryan Ash Avatar asked Sep 09 '10 18:09

Bryan Ash


People also ask

Can you call Python from Ruby?

PyCall: Calling Python functions from the Ruby language. This library provides the features to directly call and partially interoperate with Python from the Ruby language. You can import arbitrary Python modules into Ruby modules, call Python functions with automatic type conversion from Ruby to Python.

Can I use Ruby and Python together?

Using Ruby with Python - a powerful combination If you want to build a web app that looks great, delights users, and handles Big Data or uses Machine Learning, joining the forces of Python and Ruby is a very good idea.

How do I run Python in rails?

To do so, you would need to make your script into a proper Python module, start the bridge when the Rails app starts, then use RubyPython. import to get a reference to your module into your Ruby code. The examples on the gem's GitHub page are quite simple, and should be sufficient for your purpose.


2 Answers

This article gives some techniques for running Ruby code from Python which should also be applicable in the reverse direction (such as XML-RPC or pipes) as well as specific techniques for running Python code from Ruby. In particular rubypython or Ruby/Python look like they may do what you want.

like image 186
kindall Avatar answered Oct 09 '22 18:10

kindall


It sounds like you would want to use something like Apache Thrift which allows either your python or your ruby code to be a server/client and call each other. http://thrift.apache.org/

You can instantiate your objects in ruby and or in python based on your thrift definition. This is an example from the thrift website.

struct UserProfile {     1: i32 uid,     2: string name,     3: string blurb   }   service UserStorage {     void store(1: UserProfile user),     UserProfile retrieve(1: i32 uid)   } 

Basically your ruby or python will be able to call store() and retrieve() and create UserProfile objects etc.

like image 29
Martin Avatar answered Oct 09 '22 18:10

Martin