Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

erlang

I need to write my outputs from shell into a text file to keeping some required records. Can anyone please tell me how can I do this?

Thanks

like image 965
user648747 Avatar asked Mar 07 '11 19:03

user648747


3 Answers

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])).
like image 114
David Weldon Avatar answered Nov 02 '22 16:11

David Weldon


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>
like image 42
hdima Avatar answered Nov 02 '22 18:11

hdima


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.

like image 3
Roberto Aloi Avatar answered Nov 02 '22 17:11

Roberto Aloi