从Ruby调用Python
我有一个已经编译好的Python库和API文档,我想在Ruby中使用它。
请问能不能在Ruby里加载这个Python库,创建里面定义的一个类的实例,并调用这个对象的方法呢?
6 个回答
5
https://github.com/mrkn/pycall.rb
这里有一个简单的例子,展示如何调用Python的数学库中的sin函数,并将其与Ruby中的Math.sin进行比较:
require 'pycall/import'
include PyCall::Import
pyimport :math
math.sin(math.pi / 4) - Math.sin(Math::PI / 4) # => 0.0
在Ruby到Python的转换中,数字、布尔值、字符串、数组和哈希表的数据类型会自动进行转换。
5
听起来你可能想用像 Apache Thrift 这样的工具,它可以让你的 Python 或 Ruby 代码互相作为服务器和客户端进行调用。
你可以根据你的 Thrift 定义在 Ruby 或 Python 中创建对象。这是 Thrift 网站上的一个例子。
struct UserProfile {
1: i32 uid,
2: string name,
3: string blurb
}
service UserStorage {
void store(1: UserProfile user),
UserProfile retrieve(1: i32 uid)
}
简单来说,你的 Ruby 或 Python 代码可以调用 store()
和 retrieve()
方法,来创建 UserProfile
对象等等。
14
这篇文章介绍了一些方法,可以让你在Python中运行Ruby代码,这些方法也可以反过来使用(比如通过XML-RPC或者管道),另外还有一些特定的方法可以让Ruby中运行Python代码。特别是rubypython或者Ruby/Python看起来可能正好符合你的需求。