ERLANG和PYTHON互通实现过程详解

yipeiwu_com5年前Python基础

最近开发 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 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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python pandas dataframe 行列选择,切片操作方法

SQL中的select是根据列的名称来选取;Pandas则更为灵活,不但可根据列名称选取,还可以根据列所在的position(数字,在第几行第几列,注意pandas行列的position...

如何更优雅地写python代码

前言 Python 这门语言最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。但有时候我们写代码,特别是 Python 初学者,往往还是按照其它语言的思维习惯来写...

python将MongoDB里的ObjectId转换为时间戳的方法

本文实例讲述了python将MongoDB里的ObjectId转换为时间戳的方法。分享给大家供大家参考。具体分析如下: MongoDB里的_id字段前四位是时间戳的16进制表示,通过Py...

python利用正则表达式提取字符串

前言 正则表达式的基础知识就不说了,有兴趣的可以点击这里,提取一般分两种情况,一种是提取在文本中提取单个位置的字符串,另一种是提取连续多个位置的字符串。日志分析会遇到这种情况,下面我会分...

浅析Python中signal包的使用

在liunx系统中要想每隔一分钟执行一个命令,最普遍的方法就是crontab了,如果不想使用crontab,经同事指点在程序中可以用定时器实现这种功能,于是就开始摸索了,发现需要一些信号...