ERLANGとPYTHONの相互接続実現過程の詳細解


最近エリンランドを開発しましたが、文字列処理能力については言葉がないので、pythonと連携して強力な分散システムを作ることにしました。将来システム級の開発が必要な時、C++/Cを組み合わせます。
まず、エリンランドの公式文書とhttp://blog.developers.api.sina.com.cn/?tag=erlang およびhttp://kazmier.net/computer/port-howto/ ..。
24時間近く勉強して、やっと問題を完全に解決しました。townと名づけました。townは英語で市場を表しています。つまり、各種言語のここでの交流とインタラクティブを表しています。)

-module(town).
-behaviour(gen_server).
 
%% API
-export([start/0,combine/1]).
 
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {port}).
 
start() ->
 gen_server:start_link({global, ?MODULE}, ?MODULE, [], []).
stop() ->
 gen_server:cast(?SERVER, stop).
init([]) ->
 process_flag(trap_exit, true),
 Port = open_port({spawn, "python -u /home/freefis/Desktop/town.py"},[stream,{line, 1024}]),
 {ok, #state{port = Port}}.
 
handle_call({combine,String}, _From, #state{port = Port} = State) ->
 port_command(Port,String),
 receive
 {Port,{data,{_Flag,Data}}} ->
  io:format("receiving:~p~n",[Data]),
  sleep(2000),
  {reply, Data, Port}
 end.
handle_cast(stop, State) ->
 {stop, normal, State};
handle_cast(_Msg, State) ->
 {noreply, State}.
 
handle_info(Info, State) ->
 {noreply,State}.
 
terminate(_Reason, Port) ->
 ok.
 
code_change(_OldVsn, State, _Extra) ->
 {ok, State}.
 
%%--------------------------------------------------------------------
%%% Internal ---------------------------------------------------------
combine(_String) ->
 start(),
 String = list_to_binary("combine|"++_String++"
"), gen_server:call(?SERVER,{combine,String},infinity), stop().
この段はPythonのシナリオで、erlangのtown:compbine(「sentence 1+sentence 2」)が実行されると、バックグラウンドでpythonのスクリプトが起動し、処理が終わったらErring結果:sentence 1 sentence 2に戻り、終了します。

import sys
def handle(_string):
 if _string.startswith("combine|"):
  string = "".join( _string[8:].split(","))
  return string
 
"""waiting for input """
while 1:
 # Recv. Binary Stream as Standard IN
 _stream = sys.stdin.readline()
 
if not _stream: break
 # Scheme, Turn into Formal String
 inString = _stream.strip("\r
") # handle String outString = handle(inString) # send to port as Standart OUT sys.stdout.write("%s
" % (outString,)) sys.exit(0)
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。