如何让Erlang Shell打印出中文

在erlang开发项目时,经常因打印不了中文而影响调试。如何让Erlang Shell打印中文,结合网上和实践做如下整理:

1.用io:format/2的~p打印中文,出来的是unicode编码的list;

   用io:format/2的~ts打印中文,就可以打印出中文

1> io:format("test===~p~n",["测试"]).
test===[27979,35797]
ok

2> io:format("test====~ts~n",["测试"]).
test====测试
ok

2.代码中的中文都是以utf8编码过的,即把unicode编码过的list再次用utf8编码

3> xmerl_ucs:to_utf8([27979,35797]).
[230,181,139,232,175,149]

可以看到utf8编码后是一个0-255数组成的一个list,这是项目中经常输出的中文字符的日志。

3.为了输出中文,需要把utf8转换成unicode编码,即

4> unicode:characters_to_list(list_to_binary([230,181,139,232,175,149])).
[27979,35797]

5> io:format("test===~ts~n",[[27979,35797]]).
test===测试
ok

为了方便,写成一个方法,可以在项目中直接调用。

-module(print_log).
-export([log/2,
    test/0]).
 
log(Format, Data)->
    L = get_format_list(Format),
    DataList=
        lists:map(
           fun({1, X}) ->
               unicode:characters_to_list(iolist_to_binary(X));
           ({0, X}) ->
               X
           end, lists:zip(L, Data)),
    io:format(Format,DataList).


get_format_list(Format) ->
    get_format_list(Format, []).
get_format_list([], Acc) ->
    Acc;
get_format_list([$~|L], Acc) ->
    case L of
        "ts" ++ Other ->
            get_format_list(Other, Acc ++ [1]);
        "n" ++ Other ->
            get_format_list(Other, Acc);
        _ ->
            get_format_list(L, Acc ++ [0])
    end;
get_format_list([_H|L],Acc) ->
    get_format_list(L, Acc).


test()->
log("test===~ts",["测试"]).



  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值