从Erlang打开一个Python端口:没有回复消息

时间:2011-10-13 15:41:01

标签: python erlang erlang-ports

根据OTP in Action一书的第12章和Cesarini的书,我写了这个Erlang代码:

二郎:

p(Param) ->

    ?DBG("Starting~n", []),

    Cmd = "python test.py",

    Port = open_port({spawn,Cmd}, [stream,{line, 1024},  exit_status]),
    ?DBG("Opened the port: ~w~n", [Port]),

    Payload = term_to_binary(list_to_binary(integer_to_list(Param))),
    erlang:port_command(Port, Payload),

    ?DBG("Sent command to port: ~w~n", [Payload]),
    ?DBG("Ready to receive results for command: ~w~n", [Payload]),

    receive
        {Port, {data, Data}} ->
            ?DBG("Received data: ~w~n", [Data]),
            {result, Text} = binary_to_term(Data),
            Blah = binary_to_list(Text),
            io:format("~p~n", [Blah]);
        Other ->
            io:format("Unexpected data: ~p~n", [Other])

    end.

的Python:

import sys
def main():
    while True:
        line = sys.stdin.readline().strip()
        if line == "stop-good":
                return 0
        elif line == "stop-bad":
                return 1
        sys.stdout.write("Python got ")
        sys.stdout.write(line)
        sys.stdout.write("\n")
        sys.stdout.flush()
if __name__ == "__main__":
 sys.exit(main())

Erlang代码在recieve子句中挂起 - 它永远不会得到任何消息。

我还从普通的Linux shell中检查了Python - 它打印出每个用户输入(1 - “Python得1”)。

这里的错误在哪里?为什么我的Erlang代码没有得到任何回报?

2 个答案:

答案 0 :(得分:1)

你的Param是否包含Python的命令限制器? (在这种情况下,我假设换行符,“\ n”)。此外,list_to_binary / 1然后term_to_binary / 1感觉有点不对劲。 term_to_binary / 1直接(包括换行符)就足够了。

答案 1 :(得分:1)

有两点:

  • 确保Python不会缓冲您的输出,尝试在python -u中运行open_port
  • 使用term_to_binary/1binary_to_term/1将不起作用,因为他们认为Python能够编码/解码Erlang External Term Format,但似乎并非如此。如果你想走这条路,请查看ErlPort