How to know when user redirect output from erlang

2019-04-11 11:40发布

I have an sample module

    -module(helloworld).
    -compile(export_all).

    main() -> io:format("~s~s~s~n",["\e[31m","Hello world!","\e[0m"]).

When I build:

erlc helloworld.erl

After that, I run:

erl -noshell -s helloworld main -s init stop
Hello world! (with red color)
 
erl -noshell -s helloworld main -s init stop > text.txt
^[[31mHello world!^[[0m (The content in text.txt is ugly, so I don't like).

My problem is:

  1. How to know when user redirect output from erlang shell into a file?
  2. How can I write to text.txt the content just "Hello world!" not "^[[31mHello world!^[[0m"

Thanks.

标签: erlang
3条回答
爷的心禁止访问
2楼-- · 2019-04-11 11:48

I'm using io:rows/0 that returns {ok, Number} if it is a terminal or {error, enotsup} if it is not. More information here.

查看更多
劳资没心,怎么记你
3楼-- · 2019-04-11 12:00

Have a look to http://www.erlang.org/doc/man/init.html#get_arguments-0, you can check for the existence of "noshell" flag there an adopt output accordingly.

[{root,["/opt/local/lib/erlang"]},{progname,["erl"]},{home,["/Users/..."]},{noshell,[]}]]},{helloworld,main,0},{init,start_it,1},{init,start_em,1}]

查看更多
干净又极端
4楼-- · 2019-04-11 12:00

Thanks, but I don't think that can solve my problem. I use isatty in C library and solved it.

查看更多
登录 后发表回答