开发者

Erlang: How to write my outputs in a text file?

I need to write m开发者_C百科y outputs from shell into a text file to keeping some required records. Can anyone please tell me how can I do this?

Thanks


If you have the data you wish to store as a single term you can read how here. In the simplest case you can just do file:write_file(Path, Data). If your data is more complex you may want to use io_lib:fwrite/2 to format it in a more readable way. For example:

Data = [1,2,3,{car, "honda"}],
file:write_file("/tmp/foo", io_lib:fwrite("~p.\n", [Data])).


tee command can capture shell output and save it to a file:

$ erl | tee output.txt
Eshell V5.8  (abort with ^G)
1> A = 5.
5
2> 5 + A.
10
3> ^Ca

$ cat output.txt 
Eshell V5.8  (abort with ^G)
1> 5
2> 10
3>


There are many possibilities. Here's the first one which came to my mind.

In Erlang, every process is part of a group. For each group, a process - named group leader gets all the output from the group-mates. The shell process is part of the group init. So, what you could do is to change the group leader for the shell process by doing:

{ok, Log} = file:open("log", [write]),
erlang:group_leader(Log, self()).

You might want to create a dedicated process acting as group leader who manages the output in a more clever way. For example, it could wrap the file after a while or when the file reaches a certain size.

The problem with this approach is that you have to execute these lines any time you start your shell. Doing it by using the -s flag:

erl -s shell_log

where shell_log is:

-module(shell_log).

-export([start/0]).

start() ->   
    {ok, Log} = file:open("log", [write]),
    erlang:group_leader(Log, self()).

won't work, because it's still too early (init is still in {starting, started}, as reported by init:get_status()).

In the same way, doing it by using the .erlang file in your HOME directory (whose lines are automatically executed every time you start a shell) will fail for a similar reason (init is still in the {starting, applications_loaded} state).

Not sure which is the best way to circumvent this problem. I'll think about it.

Finally, this question seems a duplicate of this thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜