how to integrate a python library into a ruby on rails application

  • Last Update :
  • Techknowledgy :

To get started in your Ruby script you need to require the pycall gem and include the PyCall::Import module. You can then import a Python module using the pyimport method and call its functions directly from Ruby. For example:,Unsurprisingly to execute Python code you’ll also need Python installed! You can check what version of Python you are running with the following command:,By default pycall will use the default python on your system. You can specify a different version of Python by setting the PYTHON environment variable or calling PyCall.init with the path or basename of the python you want to use. For example:,If you don’t have Python installed you can download it from python.org or install it with your system package manager (recommended).

gem install pycall
python--version
require 'pycall/import'

include PyCall::Import

pyimport: os
p os.uname

pyimport: mimetypes
p mimetypes.guess_type('index.html')

pyimport: math
p math.degrees(math.pi / 2)
require 'pycall'

p PyCall.builtins.sum([1, 2, 3, 4])
require 'pycall'

PyCall.exec 'def double(x): return x * 2'

p PyCall.eval('double(123)')

p PyCall.eval('(1, 2, 3)')

p PyCall.eval('[pow(2, x) for x in xrange(10)]')
require 'pycall'

PyCall.init('python3')

p PyCall::PYTHON_VERSION

Suggestion : 2

Nice points Antonio, I’m 100% with you 😉 For me: 1) The reasons why Ruby is now so popular is because of Rails. If DHH would have chosen Python for writing Rails, a lot of people would ignore what Ruby is 2) I agree with Kevin: Zope is the only complete web framework at this time, but because of its complexity and the not-RDBMS architecture has a limit success,Whatever your take on the subject is, in this article I argue that Ruby on Rails is actually the best thing that ever happened to Python. Rails is a successful Ruby framework, so some may think that it would convince people to switch from Python to Ruby. In other words, naively, one could think of Rails as a Python exterminator, at least as far as web development goes (which is a big deal nowadays). This couldn’t be further from the truth. This year is going to be a great one in terms of the adoption of Python, and I think that Rails has had a positive influence in this regard., Paolo March 5, 2008 Nice points Antonio, I’m 100% with you 😉 For me: 1) The reasons why Ruby is now so popular is because of Rails. If DHH would have chosen Python for writing Rails, a lot of people would ignore what Ruby is 2) I agree with Kevin: Zope is the only complete web framework at this time, but because of its complexity and the not-RDBMS architecture has a limit success Loading... Reply ,Sure, Antonio. But I think that this is a problem with people. “Blind” people tend to sell their favorite language/platform/framework as a silver bullet. Even in the Python community.

I’m a die-hard python guy that’s used Django quite a bit. Recently, I decided I’d give Ruby another try (the 3rd? 4th?). There are a couple of features of Ruby that really appeal to me, and I’m hoping that Py3k fixes a few of the warts of the Python language.

Concerning Ruby, the past couple of weeks I’ve been using Merb quite a bit. I’m liking the simplicity and functionality of Datamapper and loving the form of Haml.

For any large project, I would choose Python over Ruby in a heartbeat. Any language can be “ugly” and “confusing” but between Py and Ruby, to me, Python’s going to end up with more straightforward and maintainable code. A lot of times the ruby community seems to like to perform little tricks which are great for golf, but for maintainable code I’m going to look at 6 months from now, Python is it.

You’re completely right about the Python community being understated and placing an emphasis on code over marketing. It’s a tragedy that the squeaky wheel seems to get
the attention, although I love to see where Ruby will end up in a few years, as it’s got a lot of potential.

Side note: One thing about Ruby that really bugs me…

irb(main): 001: 0 > def x(y)
irb(main): 002: 1 > puts y
irb(main): 003: 1 > end => nil
irb(main): 004: 0 > x(2)
2
   => nil
irb(main): 005: 0 > x = 5 => 5
irb(main): 006: 0 > x => 5
irb(main): 007: 0 > x 8
8
   => nil
irb(main): 008: 0 > x => 5

Suggestion : 3

This is the simplest solution: just run the Ruby script as an external process, using either os.system() or subprocess.Popen(). The major drawback is that it launches a new Ruby interpreter at each call, so performance is very poor if you need to call it several times.,Second, the following Python script "master.py" launches the Ruby script, then uses pipes to send data to its standard input and to receive results from its output.,There are at least two existing solutions to run Python code from Ruby, both based on embedding the Python interpreter inside Ruby:,After some time looking for solutions I figured out that it was also possible to use a brand new technology to interconnect Python and Ruby: pipes! This advanced lightweight and secure exchange protocol should be supported on the latest versions of your favorite operating systems. ;-)

# read command from standard input:
   while cmd = STDIN.gets
# remove whitespaces:
   cmd.chop!
   #
if command is "exit", terminate:
   if cmd == "exit"
break
else
   #
else evaluate command, send result to standard output:
   print eval(cmd), "\n"
# and append[end] so that master knows it 's the last line:
print "[end]\n"
# flush stdout to avoid buffering issues:
   STDOUT.flush
end
end
from subprocess
import Popen, PIPE, STDOUT

print 'launching slave process...'
slave = Popen(['ruby', 'slave.rb'], stdin = PIPE, stdout = PIPE, stderr = STDOUT)

while True:
   # read user input, expression to be evaluated:
   line = raw_input('Enter expression or exit:')
# write that line to slave 's stdin
slave.stdin.write(line + '\n')
# result will be a list of lines:
   result = []
# read slave output line by line, until we reach "[end]"
while True:
   # check
if slave has terminated:
   if slave.poll() is not None:
   print 'slave has terminated.'
exit()
# read one line, remove newline chars and trailing spaces:
   line = slave.stdout.readline().rstrip()
#print 'line:', line
if line == '[end]':
   break
result.append(line)
print 'result:'
print '\n'.join(result)
C: \test > master.py
launching slave process...
   Enter expression or exit: 3 * 4
result:
   12
Enter expression or exit: 7. type result:
   Fixnum
Enter expression or exit: 3. times {
   print "hello from Ruby!\n"
}
result:
   hello from Ruby!hello from Ruby!hello from Ruby!3
Enter expression or exit: exit
slave has terminated.

Suggestion : 4

Ruby is one of the popular programming language largely due to Rails. The Rails is a software library and an API that extends the Ruby. It is a framework for building websites. Rails is a Ruby gem (a gem is a packaged Ruby application or library). So, Rails is a package that run on top of Ruby.,RVM is similar to virtualenv in Python. RVM works virtually the same way how virtualenv works since it lets us sandbox different ruby versions and their gems.,Gemfile keeps the list of gem dependencies of our Rails application. The dependencies are met by Bundler by running bundle install.,As part of Rails ecosystem, a suite of additional tools are provides that make it easy to deploy a web application:

Using rvm (Ruby Version Manager), we can install Ruby on Ubuntu 14.04 like this:

$ sudo apt - get update
$ sudo apt - get install git - core curl zlib1g - dev build - essential libssl - dev libreadline - dev libyaml - dev libsqlite3 - dev sqlite3 libxml2 - dev libxslt1 - dev libcurl4 - openssl - dev python - software - properties
$ sudo apt - get install libgdbm - dev libncurses5 - dev automake libtool bison libffi - dev
$ curl - L https: //get.rvm.io | bash -s stable
   $ source~/.rvm/scripts / rvm
$ echo "source ~/.rvm/scripts/rvm" >> ~/.bashrc
$ rvm install 2.1 .3
$ rvm use 2.1 .3--
default
$ echo "gem: --no-ri --no-rdoc" > ~/.gemrc

The following sample shows how the Python virtualenv is working: from the current Python2, we can switch to Python3 in a sandboxed environment:

$ python
Python 2.7 .6(
      default, Jun 22 2015, 17: 58: 13) >>>

   $ virtualenv - p python3 venv3
Running virtualenv with interpreter / usr / bin / python3
Using base prefix '/usr'
New python executable in venv3 / bin / python3
Also creating executable in venv3 / bin / python
Installing setuptools, pip...done.

$ python
Python 2.7 .6(
      default, Jun 22 2015, 17: 58: 13) >>>

   $ source venv3 / bin / activate(venv3) k @laptop: ~$ python
Python 3.4 .0(
      default, Jun 19 2015, 14: 20: 21) >>>

Similarly, via RVM, we can install and use different versions of Ruby.

$ ruby - v
ruby 2.1 .2 p95(2014 - 05 - 08 revision 45877)[x86_64 - linux]

All we have to do is to specify which ruby we want to use:

$ rvm use 2.1 .3
Using / home / k / .rvm / gems / ruby - 2.1 .3

$ ruby - v
ruby 2.1 .3 p242(2014 - 09 - 19 revision 47630)[x86_64 - linux]

$ rvm list

rvm rubies

   *
   ruby - 2.1 .2[x86_64] => ruby - 2.1 .3[x86_64]

# => -current
# = * -current &&
   default
# * -
   default

We can set default version to 2.1.3:

$ rvm--
default use 2.1 .3
Using / home / k / .rvm / gems / ruby - 2.1 .3
k @laptop: ~/PyGoogle$ rvm list

rvm rubies

ruby - 2.1 .2[x86_64] = * ruby - 2.1 .3[x86_64]

# => -current
# = * -current &&
   default
# * -
   default