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学习必备知识汇总

一、变量 1.变量 •指在程序执行过程中,可变的量; •定义一个变量,就会伴随有3个特征,分别是内存ID、数据类型和变量值。 •其他语言运行完之前,一...

Python如何获取Win7,Win10系统缩放大小

这篇文章主要介绍了Python如何获取Win7,Win10系统缩放大小,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用pywin3...

python 定时器每天就执行一次的实现代码

1.实现功能 编写python脚本一直运行,判断当下是否是新的一天,如果是就执行一次任务代码 2.具体实现代码 #-*-coding:utf-8 -*- __author__ = '...

python绘制已知点的坐标的直线实例

如下所示: import matplotlib.pyplot as plt import numpy as np x = [11422,11360,11312,112...

python中使用ctypes调用so传参设置遇到的问题及解决方法

问题 近日在做一组声纹聚类时,使用了另一团队同学开发的声纹距离算法。该算法对外提供的是一组so包,需要使用方自己去使用。在python中调用纯so包一般使用ctypes类库,用起来看起来...