您好,登錄后才能下訂單哦!
ERLANG和PYTHON互通實現過程詳解?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
-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++"\n"), gen_server:call(?SERVER,{combine,String},infinity), stop().
這段是Python的腳本 當erlang中town:combine(“sentence1+sentence2”)執行時,會在后臺啟動python的腳本,處理完畢后返回給Erlang結果:sentence1sentence2,然后退出。
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\n") # handle String outString = handle(inString) # send to port as Standart OUT sys.stdout.write("%s\n" % (outString,)) sys.exit(0)
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。