如何将命令行参数传递给Erlang程序?

时间:2015-08-07 07:24:34

标签: erlang

我正在研究Erlang。如何将命令行参数传递给它?

程序文件 -

-module(program).
-export([main/0]).

main() ->
    io:fwrite("Hello, world!\n").

编译命令:

erlc Program.erl

执行命令 -

erl -noshell -s program main -s init stop

我需要通过执行命令传递参数,并希望在程序主要编写的 main 中访问它们。

3 个答案:

答案 0 :(得分:14)

$ cat program.erl
-module(program).
-export([main/1]).

main(Args) ->
    io:format("Args: ~p\n", [Args]).
$ erlc program.erl 
$ erl -noshell -s program main foo bar -s init stop
Args: [foo,bar]
$ erl -noshell -run program main foo bar -s init stop
Args: ["foo","bar"]

记录在erl man page

我建议使用escript来实现此目的,因为它具有更简单的调用。

答案 1 :(得分:3)

如果你想要“命名”参数,可能有默认值,你可以使用这个命令行(来自我制作的玩具应用程序):

erl -pa "./ebin" -s lavie -noshell -detach -width 100 -height 80 -zoom 6

lavie:start只是启动一个erlang应用程序:

-module (lavie).

-export ([start/0]).

start() -> application:start(lavie).

反过来启动我定义参数默认值的应用程序,这里是app.src(rebar build):

{application, lavie,
 [
  {description, "Le jeu de la vie selon Conway"},
  {vsn, "1.3.0"},
  {registered, [lavie_sup,lavie_wx,lavie_fsm,lavie_server,rule_wx]},
  {applications, [
                  kernel,
                  stdlib
                 ]},
  {mod, { lavie_app, [200,50,2]}}, %% with default parameters
  {env, []}
 ]}.

然后,在应用程序代码中,如果在命令行中定义了每个选项,则可以使用init:get_argument / 1获取与之关联的值。

-module(lavie_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, [W1,H1,Z1]) ->
    W = get(width,W1), 
    H = get(height,H1),
    Z = get(zoom,Z1),   
    lavie_sup:start_link([W,H,Z]).

stop(_State) ->
    % init:stop().
    ok.

get(Name,Def) ->
    case init:get_argument(Name) of
        {ok,[[L]]} -> list_to_integer(L);
        _ -> Def
    end.

明确比@Hynek提案更复杂,但它给你更多的灵活性,我发现命令行不那么不透明。

答案 2 :(得分:2)

这些不是命令行参数,但如果你想使用环境变量,那么os - 模块可能有所帮助。 os:getenv()为您提供所有环境变量的列表。 os:getenv(Var)以字符串形式提供变量的值,如果Var不是环境变量,则返回false。

应在启动应用程序之前设置这些env变量。

我总是使用这样的成语来启动(在bash-shell上):

export PORT=8080 && erl -noshell -s program main