最近開發 Erlang ,對其字符串處理能力無言至極,于是決定把它和python聯合起來,打造一個強力的分布式系統,等將來需要系統級開發時,我再把 C++/C組合進來.
首先參考了 Erlang 官方文檔和 http://blog.developers.api.sina.com.cn/?tag=erlang 以及 http://kazmier.net/computer/port-howto/ .
研讀了將近24個小時, 才終于完全把問題解決. 起名為town,town在英文里表示集市,也就是代表各種語言在這里的交流與互動。) )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
- module(town). - behaviour(gen_server). % % API - export([start / 0 ,combine / 1 ]). % % gen_server callbacks - 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({ global , ?MODULE}, ?MODULE, [], []). stop() - > gen_server:cast(?SERVER, stop). init([]) - > process_flag(trap_exit, true), Port = open_port({spawn, "python -u /home/freefis/Desktop/town.py" },[stream,{line, 1024 }]), {ok, #state{port = Port}}. handle_call({combine,String}, _From, #state{port = Port} = State) -> port_command(Port,String), receive {Port,{data,{_Flag,Data}}} - > io: format ( "receiving:~p~n" ,[Data]), 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(), String = list_to_binary( "combine|" + + _String + + "\n" ), gen_server:call(?SERVER,{combine,String},infinity), stop(). |
這段是Python的腳本 當erlang中town:combine(“sentence1+sentence2”)執行時,會在后臺啟動python的腳本,處理完畢后返回給Erlang結果:sentence1sentence2,然后退出。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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 # Scheme, Turn into Formal String inString = _stream.strip( "\r\n" ) # handle String outString = handle(inString) # send to port as Standart OUT sys.stdout.write( "%s\n" % (outString,)) sys.exit( 0 ) |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://coolshell.cn/articles/1313.html