Created
December 22, 2016 15:54
-
-
Save ahirschberg/4b85952f962b0e58f29439acd832ab99 to your computer and use it in GitHub Desktop.
test ruby -> python interop via pipes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'open3' | |
require 'json' | |
require 'pry' | |
module Interop | |
def self.send json | |
result, status = Open3.capture2("python slave.py", | |
stdin_data: json) | |
status.to_s # noop, get rid of unused variable warning | |
JSON.parse(result)["return"] | |
end | |
end | |
module Model | |
def self.match query, num_results, min_score | |
Interop.send JSON.generate({method: "match", | |
args: [query, num_results, min_score] | |
}) | |
end | |
end | |
thread_pool = [] | |
# simulate multiple users | |
10.times do |i| | |
thread_pool << Thread.new do | |
puts "Calling interop from thread #{i}" | |
# Call python: | |
# It looks like a regular method call! | |
result = Model.match "i", i, 0 | |
puts "Got result back: #{result}" | |
end | |
end | |
thread_pool.each {|t| t.join} | |
# open an interactive shell | |
binding.pry |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from json import loads, dumps | |
from sys import stdin, stdout | |
class Model: | |
def match(self, query, n, min_score): | |
return ["Mocked model.match called with:", query, n, min_score] | |
model_instance = Model() | |
switcher = { | |
"match": getattr(model_instance, "match") | |
} | |
caller_map = loads(stdin.read()) | |
method_desired = caller_map["method"] | |
method_args = caller_map["args"] | |
retval = switcher[method_desired](*method_args) | |
stdout.write(dumps({'return': retval})) | |
stdout.flush() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment