如何在 Elixir 中“检查文件”(或字符串)?

Yak*_*ovL 4 debugging elixir

在 Elixir 中,我们可以IO.inspect anyStructure得到anyStructure\ 的内部结构打印到输出中。是否有类似的方法将其输出到文件(或者,作为更灵活的解决方案,输出到字符串)?

\n

我浏览了一些关于调试io的文章的文章,但没有看到解决方案。我也尝试过

\n
{:ok, file} = File.open("test.log", [:append, {:delayed_write, 100, 20}])\nstructure = %{ a: 1, b: 2 }\nIO.binwrite(file, structure)\nFile.close file\n
Run Code Online (Sandbox Code Playgroud)\n

但这会导致

\n
no function clause matching in IO.binwrite/2 [...]\ndef binwrite(device, iodata) when is_list(iodata) or is_binary(iodata)\n
Run Code Online (Sandbox Code Playgroud)\n

我\xe2\x80\x99ve还用谷歌搜索了一些“elixir序列化”和“elixir对象到字符串”,但没有找到任何有用的东西(比如:erlang.term_to_binary返回,嗯,二进制)。有没有一种简单的方法可以获得相同的结果IO.inspect打印到文件或字符串中相同的结果?

\n

Mik*_*nov 6

已经有inspect/2函数了(和 不一样IO.inspect),就用它吧:

#> inspect({1,2,3})
"{1, 2, 3}"

#> h inspect/2
                         def inspect(term, opts \\ [])

  @spec inspect(
          Inspect.t(),
          keyword()
        ) :: String.t()

Inspects the given argument according to the Inspect protocol. The second
argument is a keyword list with options to control inspection.


Run Code Online (Sandbox Code Playgroud)

之后你可以对字符串做任何你想做的事情。