Erlang和Python互通
最近开发 Erlang ,对其字符串处理能力无言至极,于是决定把它和python联合起来,打造一个强力的分布式系统,等将来需要系统级开发时,我再把 C++/C组合进来.
首先参考了 Erlang 官方文档和 http://blog.developers.api.sina.com.cn/?tag=erlang 以及 http://kazmier.net/computer/port-howto/ .
研读了将近24个小时, 才终于完全把问题解决. 起名为town,town在英文里表示集市,也就是代表各种语言在这里的交流与互动。) )
[erl]-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().[/erl]
这段是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)
转载于酷壳CoolShell 无删改 仅以此纪念陈皓(左耳朵耗子)
大家好,我是做国内彩票量化分析师,分析的彩票是:七星彩、排列五、福彩 3D ,大概有 12 年经验。我想认真找创业的,认真谈。 如果你: 1 、有很好的技术 2 、想把技术分…
换回 win 了,习惯了 linux 命令,用不惯 cmd 那一套,win 下使用 linux 命令的方法有哪些?不想使用 wsl ,还有其他的方法吗? 装个 git bas…
好久没有写一些微观方面的文章了,今天写一篇关于CPU Cache相关的文章,这篇文章比较长,主要分成这么几个部分:基础知识、缓存的命中、缓存的一致性、相关的代码示例和延伸阅读。…
合速度