Guest User

py-erl

a guest
Feb 19th, 2011
701
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.97 KB | None | 0 0
  1. -module(example1).
  2. -export([start/0, stop/0]).
  3. -export([twice/1, sum/2, divide/2, listify/1, delistify/1]).
  4.  
  5. start() ->
  6.     spawn(fun() ->
  7.         register(example1, self()),
  8.     process_flag(trap_exit, true),
  9.     Port = open_port({spawn, "python \"E:/User files/nskoric/PortablePython_1.1_py2.6.1/simulator/simulator/erlang.py\"" }, [{packet, 2}]),
  10.     loop(Port)
  11.     end).
  12.  
  13. stop() ->
  14.     example1 ! stop.
  15.  
  16. twice(X) -> call_port({twice, X}).
  17. sum(X,Y) -> call_port({sum, X, Y}).
  18. divide(X,Y) -> call_port({divide, X, Y}).
  19.  
  20. call_port(Msg) ->
  21.     example1 ! {call, self(), Msg},
  22.     receive
  23.         {example1, Result} ->
  24.         Result
  25.     end.
  26.  
  27.  
  28. loop(Port) ->
  29.     receive
  30.     {'EXIT', Port, Reason} ->
  31.         io:format("Port ~p terminated: ~p~n", [Port, Reason]);
  32.         {call, Caller, Msg} ->
  33.         Port ! {self(), {command, encode(Msg)}},
  34.         io:format("loop sent to port, waiting~n"),
  35.         receive
  36.             {Port, {data, Data}} ->
  37.             io:format("exact answer received~n"),
  38.             Caller ! {example1, decode(Data)};
  39.             {Port, Burek} ->
  40.             io:format("some 1 answer received:~p~n", [Burek]),
  41.             Caller ! {example1, 10};
  42.             Burek ->
  43.             io:format("some 2 answer received:~p~n", [Burek]),
  44.             Caller ! {example1, 10}
  45.         after 1000 ->
  46.                 io:format("timeouted~n"),
  47.             Caller ! {example1, 10}
  48.         end,
  49.         loop(Port);
  50.     stop ->
  51.         Port ! {self(), close},
  52.         receive
  53.             {Port, closed} ->
  54.             exit(normal)
  55.         end;
  56.     {'EXIT', Port, Reason} ->
  57.         exit({port_terminated,Reason})
  58.     end.
  59.  
  60. encode({twice, X}) -> [1, X];
  61. encode({sum, X, Y}) -> [2, X, Y];
  62. encode({divide, X, Y}) -> [3, X, Y].
  63.  
  64. decode([Int]) -> Int;
  65. decode(List) -> List.
  66.  
  67. listify(0) -> [0];
  68. listify(Int) -> lists:reverse(listify1(Int)).
  69. listify1(0) -> [];
  70. listify1(Int) -> [Int rem 16#100 | listify1(Int div 16#100)].
  71.  
  72. delistify(List) -> delistify1(lists:reverse(List)).
  73. delistify1([Head]) -> Head;
  74. delistify1([Head|Rest]) ->  Head + 16#100 * delistify1(Rest).
Advertisement
Add Comment
Please, Sign In to add comment