本文介绍了从Erlang打开Python端口:无回复消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于《 OTP在行动》一书和Cesarini的书的第12章,我编写了以下Erlang代码:

Based on Chapter 12 of the OTP in Action book and Cesarini's book I wrote this Erlang code:

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代码在recipve子句中挂起-它从不获取任何内容消息。

The Erlang code suspends at the recieve clause - it never gets any message.

我还从常规的Linux shell中检查了Python-它打印出每个用户输入的内容(1- Python得到1)。

I have also checked Python from a regular Linux shell - it prints out every user input (1 - "Python got 1").

这里的错误在哪里?为什么我的Erlang代码无法收回任何东西?

Where is the mistake here? Why doesn't my Erlang code get anything back?

推荐答案

有两点:


  • 确保Python不缓冲您的输出,请尝试在 open_port python -u / code>

  • 使用 term_to_binary / 1 binary_to_term / 1 无效,因为他们认为Python能够对,似乎并非如此。如果您想走这条路线,请查看

  • make sure that Python does not buffer your output, try running python -u in open_port
  • using term_to_binary/1 and binary_to_term/1 won't work, since they assume that Python is able to encode/decode Erlang External Term Format, which does not seem to be the case. If you want to go this route, check out ErlPort

这篇关于从Erlang打开Python端口:无回复消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 01:08