ERLANG和PYTHON互通实现过程详解
Python  /  管理员 发布于 7年前   173
最近开发 Erlang ,对其字符串处理能力无言至极,于是决定把它和python联合起来,打造一个强力的分布式系统,等将来需要系统级开发时,我再把 C++/C组合进来.
首先参考了 Erlang 官方文档和 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++"\n"), gen_server:call(?SERVER,{combine,String},infinity), stop().
这段是Python的脚本 当erlang中town:combine(“sentence1+sentence2”)执行时,会在后台启动python的脚本,处理完毕后返回给Erlang结果:sentence1sentence2,然后退出。
import 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 # 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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号