Erlastic
项目描述
用法
Erlastic 允许您将 Python 对象序列化/反序列化为 erlang 二进制项。
基本用法是
import erlastic py_struct = erlastic.decode(binary_term) binary = erlastic.encode(py_struct)
Erlang 端口通信使用
库还包含一个函数,可以在 Erlang 端口上使用 Python 和 erlastic 通信 erlang 二进制项: port_communication() 返回 (mailbox,port)。它们都是 Python 协程(执行生成器),因此您可以使用 Python 抽象与 Erlang 协程进行通信
mailbox 在 stdin 中等待端口消息,遍历从二进制 Erlang 项格式解码的消息。
port 等待 send(python_struct)(https://docs.pythonlang.cn/3.3/reference/expressions.html#generator.send)然后将 python_struct 编码为二进制项格式并发送到 Erlang 端口通过 stdout。
例如,如果您想创建一个接收元组 {A,B} 并返回 {ok,A/B} 或 {error,divisionbyzero} 的 Python 服务器,您可以在 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 端,使用 -u python 参数以防止 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)])
或使用 elixir
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)}"
项目详情
关闭
basho-erlastic-2.1.1.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | d1596a881437f2be71a8426efed1566b7faefb97234cb21440700ecc8367c545 |
|
MD5 | 25880fdae85b0bcf8c78fe41d2236c1d |
|
BLAKE2b-256 | f12af1c47fa0f03f5c7ef7550d23631fe4dc904259e3a2fe8b56fa9d79be9629 |