码迷,mamicode.com
首页 > 编程语言 > 详细

elang和python互通的例子

时间:2014-11-02 10:36:45      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   for   sp   div   

抄袭自http://www.erlangsir.com/2011/04/14/python-%E5%92%8Cerlang%E4%BA%92%E9%80%9A%E4%BE%8B%E5%AD%90/

 

town.erl

-module(town).
-behaviour(gen_server).

-export([start/0, combine/1]).
-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({local, ?MODULE}, ?MODULE, [], []).

stop() ->
    gen_server:cast(?MODULE, stop).

init([]) ->
    process_flag(trap_exit, true),
    Port = open_port({spawn,
              "python -u ./town.py"},
        [stream, {line, 1024}]
    ),

    {ok, #state{port = Port}}.

handle_call({combine, Str}, _From, #state{port = Port} = State) ->
    io:format("here~n"),
    port_command(Port, Str),

    receive
        {Port, {data, {_Flag, Data}}} ->
            io:format("receiving:~p~n", [Data]),
            timer: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(),
    Str = list_to_binary("combine|" ++ _String ++ "\n"),
    gen_server:call(?MODULE, {combine, Str}).

 

town.py

#! /usr/bin/python
# Filename : town.py

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
    inString = _stream.strip("\r\n")
    outString = handle(inString)
    sys.stdout.write("%s\n" % (outString,))
    sys.exit(0)

 

测试

Eshell V6.2  (abort with ^G)
1> town:combine("aaa+bbb").
here
receiving:"aaa+bbb"
"aaa+bbb"
2> 

 

elang和python互通的例子

标签:style   blog   http   io   color   ar   for   sp   div   

原文地址:http://www.cnblogs.com/ziyouchutuwenwu/p/4068389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!