首页 > 代码库 > elang和python互通的例子
elang和python互通的例子
抄袭自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}.% Internalcombine(_String) -> start(), Str = list_to_binary("combine|" ++ _String ++ "\n"), gen_server:call(?MODULE, {combine, Str}).
town.py
#! /usr/bin/python# Filename : town.pyimport sysdef 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").herereceiving:"aaa+bbb""aaa+bbb"2>
elang和python互通的例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。