Ruby 的 Python 接口:puby

jopen 11年前發布 | 26K 次閱讀 Python Python開發

puby 是 Ruby 解釋器的 Python 接口。

示例代碼

解析 HTML

# python                                   # # ruby
from puby import Object as rb              # 
rb.require("nokogiri")                     # require "nokogiri"
rb.require("open-uri")                     # require "open-uri"

url = "http://www.google.com/search?q=foo" # url = "http://www.google.com/search?q=foo"
doc = rb.Nokogiri.HTML.parse(rb.open(url)) # doc = Nokogiri::HTML.parse(open(url))

for link in doc.css("h3.r a"):             # doc.css("h3.r a").each do |link|
    print link.content()                   #     puts link.content
                                           # end
執行 JavaScript:
from puby import Object as rb              # 
rb.require('v8')                           # require "v8"

ctx = rb.V8.Context.new()                  # ctx = V8::Context.new
print ctx.eval("'Xzibit ' + 7 * 6")        # puts ctx.eval "'Xzibit ' + 7 * 6"
運行 Web 服務器:
from puby import Object as rb              # 
rb.require("rack")                         # require "rack"
                                           # 
def application(env):                      # def application(env)
    return [200,                           #   [200,
            {"Content-Type": "text/html"}, #    {"Content-Type" => "text/html"},
            ["Hello Puby!"]]               #    ["Hello Puby!"]]
                                           # end
rb.Rack.Handler.Thin.run(application)      # Rack::Handler::Thin.run method(:application)
回調示例:
from puby import Object as rb, RbCallback

rb.eval("""
class TestObj
    def save_callback cb
        @cb = cb
    end
    def call_callback x
        @cb.call(x)
    end
end
""")
obj = rb.TestObj.new()

def callback(x):
    return x+1

callback_rb = RbCallback(callback)
obj.save_callback(callback_rb)
print obj.call_callback(5)

項目主頁:http://www.baiduhome.net/lib/view/home/1372646806456

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!