ERLANG和PYTHON互通实现过程详解

发布时间:2021-06-01 18:24:18 作者:Leah
来源:亿速云 阅读:111

ERLANG和PYTHON互通实现过程详解?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

-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)

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. erlang和rabbitmq安装(0)
  2. [erl] erlang 进程注册和注销

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

erlang python

上一篇:pandas数据筛选和csv操作的实现方法

下一篇:使用pandas怎么实现时间格式转换

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》