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

How can I pass command-line arguments to a Erlang program?

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

程序文件-

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

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

编译命令:

erlc Program.erl

执行命令-

erl -noshell -s program main -s init stop

我需要通过执行命令传递参数,并想在main中访问它们,写在程序的main.

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

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

我总是用这样的成语开始(在bash-shell):

export PORT=8080 && erl -noshell -s program main
$ 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,因为它的调用更简单。

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

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(钢筋构建):

{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 的提议更复杂,但它给了你更大的灵活性,而且我发现命令行不那么不透明。