Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(example1).
- -export([start/0, stop/0]).
- -export([twice/1, sum/2, divide/2, listify/1, delistify/1]).
- start() ->
- spawn(fun() ->
- register(example1, self()),
- process_flag(trap_exit, true),
- Port = open_port({spawn, "python \"E:/User files/nskoric/PortablePython_1.1_py2.6.1/simulator/simulator/erlang.py\"" }, [{packet, 2}]),
- loop(Port)
- end).
- stop() ->
- example1 ! stop.
- twice(X) -> call_port({twice, X}).
- sum(X,Y) -> call_port({sum, X, Y}).
- divide(X,Y) -> call_port({divide, X, Y}).
- call_port(Msg) ->
- example1 ! {call, self(), Msg},
- receive
- {example1, Result} ->
- Result
- end.
- loop(Port) ->
- receive
- {'EXIT', Port, Reason} ->
- io:format("Port ~p terminated: ~p~n", [Port, Reason]);
- {call, Caller, Msg} ->
- Port ! {self(), {command, encode(Msg)}},
- io:format("loop sent to port, waiting~n"),
- receive
- {Port, {data, Data}} ->
- io:format("exact answer received~n"),
- Caller ! {example1, decode(Data)};
- {Port, Burek} ->
- io:format("some 1 answer received:~p~n", [Burek]),
- Caller ! {example1, 10};
- Burek ->
- io:format("some 2 answer received:~p~n", [Burek]),
- Caller ! {example1, 10}
- after 1000 ->
- io:format("timeouted~n"),
- Caller ! {example1, 10}
- end,
- loop(Port);
- stop ->
- Port ! {self(), close},
- receive
- {Port, closed} ->
- exit(normal)
- end;
- {'EXIT', Port, Reason} ->
- exit({port_terminated,Reason})
- end.
- encode({twice, X}) -> [1, X];
- encode({sum, X, Y}) -> [2, X, Y];
- encode({divide, X, Y}) -> [3, X, Y].
- decode([Int]) -> Int;
- decode(List) -> List.
- listify(0) -> [0];
- listify(Int) -> lists:reverse(listify1(Int)).
- listify1(0) -> [];
- listify1(Int) -> [Int rem 16#100 | listify1(Int div 16#100)].
- delistify(List) -> delistify1(lists:reverse(List)).
- delistify1([Head]) -> Head;
- delistify1([Head|Rest]) -> Head + 16#100 * delistify1(Rest).
Advertisement
Add Comment
Please, Sign In to add comment