zoukankan      html  css  js  c++  java
  • elang和python互通的例子

    抄袭自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 ++ "
    "),
        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("
    ")
        outString = handle(inString)
        sys.stdout.write("%s
    " % (outString,))
        sys.exit(0)

    测试

    Eshell V6.2  (abort with ^G)
    1> town:combine("aaa+bbb").
    here
    receiving:"aaa+bbb"
    "aaa+bbb"
    2> 
  • 相关阅读:
    mysqlnd cannot connect to MySQL 4.1+ using old authentication
    nginx中查看关于php的配置和php-fpm的重启等操作
    nginx中查看关于php的配置和php-fpm的重启等操作
    linux面试题1
    linux笔试
    面试题
    shell脚本实例
    shell脚本
    mysql主从复制
    Discuz!NT静态文件缓存(SQUID)
  • 原文地址:https://www.cnblogs.com/ziyouchutuwenwu/p/4068389.html
Copyright © 2011-2022 走看看