io:fread 对于 unicode 字符不适用于 -noshell

io:fread for unicode characters does not work with -noshell

我正在尝试使用 io:fread.

读取 unicode 字符(超出 latin1 范围)

下面的代码在 shell 模式下工作正常:

Eshell V5.10.4  (abort with ^G) 

1> io:fread("Input some Unicode characters: ", "~ts").

Input some Unicode characters: 呵呵

{ok,[[21621,21621]]}

然而,当使用 -noshell 标志时,它 returns 另一个列表:

$ erl -noshell -eval "io:format(\"~p\", [io:fread(\"Input: \", \"~ts\")])."

Input: 呵呵

{ok,[[229,145,181,229,145,181]]}

有谁知道为什么会这样?

来自二郎 documentation,

When Erlang is started with -oldshell or -noshell, the I/O-server for standard_io is default set to bytewise encoding, while an interactive shell defaults to what the environment variables says

With the io:setopts/2 function you can set the encoding of a file or other I/O-server...

因此,io:setopts/2应添加如下;

$ erl -noshell -eval "io:setopts(standard_io, [{encoding, unicode}]), io:format(\"~p\", [io:fread(\"Input: \", \"~ts\")])."
Input: 呵呵
{ok,[[21621,21621]]}