2010-01-26 112 views

回答

8

只需運行它erl -noinput -s module function -s init stop > file

下面是一個例子。

二郎代碼:

-module(test).  
-compile(export_all). 

function() -> 
    io:fwrite("Hello world!~n"). 

在外殼:

$ erlc test.erl 
$ erl -noinput -s test function -s init stop > test.txt 
$ cat test.txt 
Hello world! 
2

您還可以使用IODevice參數IO:使用fwrite/3,讓它具有原子值standard_io當你不不想讓它指向某個文件。否則給它的文件。

請參閱io module文檔的「標準輸入/輸出」部分。

11

當一個進程調用io:format()和類似的函數時,進程發送IO請求消息到它的group_leader進程。所以簡單的破解就是打開一個文件,並將其設置爲生成輸出的進程的group_leader。以下是將shell進程的輸出重定向到文件的示例。

1> {ok, F} = file:open("z", [write]). 
{ok,<0.36.0>} 
2> group_leader(F, self()). 
3> io:format("Where am I going to appear?~n").  
4> 

這隻會重定向當前的shell程序,所以你必須設置爲group_leader您想重定向到文件中的所有進程。

該解決方案可以通過生成一個服務器進程,其代理的IO請求消息輪換文件細化過程,例如,等

+0

不錯的破解!可能相當有幫助 – gleber 2010-01-26 21:18:20

1

您可以用解析變換重新編譯代碼,轉換調用像

io:format("~p~n", "Hello world!") 

到像

io:format(whereis(my_output_file), "~p~n", "Hello world!") 

呼叫另外,您需要添加到您的啓動代碼這一點,就大功告成了:

{ok, F} = file:open("file", [write]), 
register(my_output_file, F),