如何用长生不老瓷向python脚本发送消息?

2024-09-28 21:49:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试学习如何使用porcelain module从长生不老药中进行互操作。在

所以我做了一个简单的例子:

我有一个长生不老药的功能是这样的:

defmodule PythonMessenger do
  alias Porcelain.Process, as: Proc
  alias Porcelain.Result

  def test_messages do
    proc = %Proc{pid: pid} =
      Porcelain.spawn_shell("python ./python_scripts/reply_to_elixir.py",
        in: :receive, out: {:send, self()})

    Proc.send_input(proc, "Greetings from Elixir\n")

    data = receive do
      {^pid, :data, :out, data} -> data
    end

    IO.inspect data

    Proc.send_input(proc, "Elixir: I heard you said \"#{data}\"\n")

    data = receive do
      {^pid, :data, data} -> data
    end

    IO.inspect data

    Proc.send_input(proc, "Please quit\n")

    data = receive do
      {^pid, :data, data} -> data
    end

    IO.inspect data
  end
end

以及如下所示的python脚本:

^{pr2}$

但这行不通。python脚本永远不会退出。 如果只读一行:

  line = sys.stdin.readline()

它很好用。在

有什么问题吗,有什么想法吗?在


Tags: iosendinputdataaliasprocoutpid
1条回答
网友
1楼 · 发布于 2024-09-28 21:49:21

您需要传递-u来禁用sys.stdin.readline()中的缓冲。在交互式运行程序时,您不会看到这一点,但是当程序在没有TTY的情况下生成时,您将看到它。由于默认的缓冲区,Python进程没有为"Greetings from Elixir\n"之类的短消息打印任何内容,而且由于receive表达式,Elixir代码永远阻塞,等待Python进程打印某些内容。在

来自man python

   -u     Force  stdin,  stdout  and stderr to be totally unbuffered.  On systems where it matters, also
          put stdin, stdout and stderr in binary mode.  Note that there is internal buffering in  xread-
          lines(),  readlines()  and file-object iterators ("for line in sys.stdin") which is not influ-
          enced by this option.  To work around this, you will want to use "sys.stdin.readline()" inside
          a "while 1:" loop.

你在第二和第三个receive模式中也有一些错误。以下是对我有用的代码:

^{pr2}$

输出:

"Greetings from Elixir\n\n"
"Elixir: I heard you said \"Greetings from Elixir\n\n\n\n"
"\"\n\n"

相关问题 更多 >