Recently I developed Erlang, and I was speechless about its string handling ability, so I decided to combine it with python to create a powerful distributed system, and when I need system-level development in the future, I'll put C++/C into the mix.
First refer to the official Erlang documentation and /?tag=erlang and /computer/port-howto/ .
It took nearly 24 hours of study to completely solve the problem. The name is town, which means a marketplace in English, and also represents the exchange and interaction of various languages here). )
-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/"},[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().
This is a Python script When town:combine("sentence1+sentence2") is executed in erlang, a python script is started in the background, processed and returned to Erlang with the result. sentence1sentence2, and then exits.
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 = () 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 ("%s\n" % (outString,)) (0)
This is the whole content of this article.