抄袭自http://www.erlangsir.com/2011/04/14/python-%E5%92%8Cerlang%E4%BA%92%E9%80%9A%E4%BE%8B%E5%AD%90/
town.erl
-module(town). -behaviour(gen_server). -export([start/0, combine/1]). -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({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:cast(?MODULE, stop). init([]) -> process_flag(trap_exit, true), Port = open_port({spawn, "python -u ./town.py"}, [stream, {line, 1024}] ), {ok, #state{port = Port}}. handle_call({combine, Str}, _From, #state{port = Port} = State) -> io:format("here~n"), port_command(Port, Str), receive {Port, {data, {_Flag, Data}}} -> io:format("receiving:~p~n", [Data]), timer: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(), Str = list_to_binary("combine|" ++ _String ++ "\n"), gen_server:call(?MODULE, {combine, Str}).
town.py
#! /usr/bin/python # Filename : town.py 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 inString = _stream.strip("\r\n") outString = handle(inString) sys.stdout.write("%s\n" % (outString,)) sys.exit(0)
测试
Eshell V6.2 (abort with ^G) 1> town:combine("aaa+bbb"). here receiving:"aaa+bbb" "aaa+bbb" 2>
时间: 2024-10-11 16:04:16