rubypython gem

description

RubyPython is a bridge between the Ruby and Python interpreters. It embeds a running Python interpreter in the Ruby application’s process using FFI and provides a means for wrapping, converting, and calling Python objects and methods.

RubyPython uses FFI to marshal the data between the Ruby and Python VMs and make Python calls. You can:

  • Inherit from Python classes.

  • Configure callbacks from Python.

  • Run Python generators (on Ruby 1.9.2 or later).

where

The RubyPython homepage, project description, and main downloads can be found onRubyForge.

Source is kept in sync between Bitbucket and GitHub, but the Bitbucket repository is the canonical repository and where the issue tracker resides. We use Hg-Git to keep the two repositories in sync.

synopsis

RubyPython is fairly easy to start using; there are three phases to its use:

  1. Start the Python interpreter (RubyPython.start).

  2. Import and use Python code (RubyPython.import).

  3. Stop the Python interpreter (RubyPython.stop).

There are also two methods, RubyPython.session and RubyPython.run that will start before running the code provided in the block and stop it afterwards.

basic usage

require "rubypython"

RubyPython.start # start the Python interpreter

cPickle = RubyPython.import("cPickle")
p cPickle.dumps("Testing RubyPython.").rubify

RubyPython.stop # stop the Python interpreter

specific python version

require "rubypython"

RubyPython.start(:python_exe => "python2.7") # Can also be a full path

cPickle = RubyPython.import("cPickle")
p cPickle.dumps("Testing RubyPython.").rubify

RubyPython.stop # stop the Python interpreter

virtualenv

# Easy
RubyPython.start_from_virtualenv("/path/to/virtualenv")

# Or verbose
RubyPython.start(:python_exe => "/path/to/virtualenv/bin/python")
RubyPython.activate

iterator support

# Python
def readfile():
  for line in open("/some/file"):
    yield line

# Ruby
readfile.to_enum.each do |line|
  puts line
end

# Python
def iterate_list():
  for item in [ 1, 2, 3 ]:
    yield item

# Ruby
items = []
iterate_list.to_enum.each { |item| items << item }
puts items == [ 1, 2, 3 ] # => true

python to ruby callbacks

# Python
def simple_callback(callback, value):
  return callback(value)

# Ruby
simple_callback(lambda { |v| v * v }, 4) # => 16

def triple(v)
  v * 3
end

simple_callback(method(:triple), 4) # => 12

python-style generators

posted on 2012-04-01 16:51  lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/archive/2012/04/01/2429029.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值