在 Elixir 中,我们可以IO.inspect anyStructure得到anyStructure\ 的内部结构打印到输出中。是否有类似的方法将其输出到文件(或者,作为更灵活的解决方案,输出到字符串)?
我浏览了一些关于调试和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\nRun Code Online (Sandbox Code Playgroud)\n但这会导致
\nno function clause matching in IO.binwrite/2 [...]\ndef binwrite(device, iodata) when is_list(iodata) or is_binary(iodata)\nRun Code Online (Sandbox Code Playgroud)\n我\xe2\x80\x99ve还用谷歌搜索了一些“elixir序列化”和“elixir对象到字符串”,但没有找到任何有用的东西(比如:erlang.term_to_binary返回,嗯,二进制)。有没有一种简单的方法可以获得相同的结果IO.inspect打印到文件或字符串中相同的结果?
已经有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)
之后你可以对字符串做任何你想做的事情。
| 归档时间: |
|
| 查看次数: |
1184 次 |
| 最近记录: |