[erlang-questions] Erlang module for "controlling" (linux/unix) commands?
Boris Mühmer
boris.muehmer@REDACTED
Wed Sep 8 19:48:38 CEST 2010
I'm using the following code (test_command/0 is my entry point for the
tests):
%%% ================================================================
%%% test_command
%%% ================================================================
test_command() ->
MysqlCmd = "/usr/local/bin/mysql",
Args =
[
"--host=mysql-host"
,"--user=MySqlSuperUser"
,"--password=MySecretPassword"
,"-e"
,"SELECT user,password,host FROM mysql.user;"
],
Result = execute_command(MysqlCmd, Args),
Line =
"----------------------------------------------------------------------------",
io:format("~s~nResult:~n~p~n~s~n",[Line, Result, Line]),
ok.
%%% ================================================================
%%% execute_command
%%% ================================================================
execute_command(Command, Arguments) when is_list(Command),
is_list(Arguments) ->
PortSettings =
[
{args, Arguments}
,exit_status
,stderr_to_stdout
,{line, 1024}
],
Port = erlang:open_port({spawn_executable, Command}, PortSettings),
execute_command_loop(Port, []).
%%% ================================================================
%%% execute_command_loop
%%% ================================================================
execute_command_loop(Port, Data) ->
receive
{Port,{exit_status, ExitStatus}} ->
{ExitStatus, lists:reverse(Data)};
{Port,{data, NewData}} ->
execute_command_loop(Port, [NewData | Data]);
Other ->
io:format("Other:~p~n",[Other]),
execute_command_loop(Port, Data)
end.
I'm not sure if this is "good" code... it works... also when errors occur
(e.g. "mysql.users" instead of "mysql.user", or adding a non-existing
column).
Is it possible to circumvent the "lists:reverse/1" call in
"execute_command_loop/2"???
- boris
More information about the erlang-questions
mailing list