顽强的
basho-erlastic的Python项目详细描述
用法
erlastic允许您将python对象序列化/反序列化为erlang binary term。
基本用法是:
import erlastic py_struct = erlastic.decode(binary_term) binary = erlastic.encode(py_struct)
erlang端口通信用法
该库还包含一个函数,在 用于通信erlang二进制项的erlang端口:port_communication() 返回(mailbox,port)。它们都是python协同程序 (执行的生成器)以便可以使用 python抽象:
- mailbox在stdin中等待端口消息,在消息上迭代 从二进制erlang术语格式解码。
- port等待send(python_struct) (http://docs.python.org/3.3/reference/expressions.html#generator.send) 然后将python_struct编码为二进制术语格式并将其发送到 通过stdout的erlang端口。
例如,如果你想创建一个python服务器 元组{a,b}并返回{error,divisionbyzero}的{ok,a/b},您可以 在python端使用:
from erlastic import port_connection,Atom as A mailbox,port = port_connection() for (a,b) in mailbox: port.send((A("ok"),a/b) if b!=0 else (A("error"),A("divisionbyzero")))
在erlang端,使用-upython参数防止python 输出缓冲,使用4字节的数据包长度,因为它是 python生成器使用的配置。
Port = open_port({spawn,"python3 -u add_server.py"},[binary,{packet,4}]), Div = fun(A,B)-> Port ! {self(),{command,term_to_binary({A,B})}}, receive {Port,{data,Bin}}->binary_to_term(Bin) after 1000->{error,timeout} end end, io:format("send {A,B}=~p, python result : ~p~n",[{32,10},Div(32,10)]), io:format("send {A,B}=~p, python result : ~p~n",[{2,0},Div(2,0)]), io:format("send {A,B}=~p, python result : ~p~n",[{1,1},Div(1,1)])
或在灵丹妙药中:
port = Port.open({:spawn,'python3 -u add_server.py'},[:binary|[packet: 4]]) div = fn(a,b)-> port <- {self,{:command,term_to_binary({a,b})}} receive do {_,{:data,b}} -> binary_to_term(b) after 100->{:error,:timeout} end end IO.puts "send {a,b}={32,10}, python result : #{inspect div.(32,10)}" IO.puts "send {a,b}={2,0}, python result : #{inspect div.(2,0)}" IO.puts "send {a,b}={1,1}, python result : #{inspect div.(1,1)}"