erlang的脚本执行---escript

1.概述:

    作为程序员对于脚本语言应该很熟悉了,脚本语言的优点很多,如快速开发、容易编写、实时开发和执行, 我们常用的脚本有Javascript、shell、python等,我们的erlang语言也有支持脚本运行的工具---escript,它支持在不编译的情况下,直接从命令行运行代码。

2. 示例:

    编写了一个使用escript来解析application文件的脚本代码,为了读取vsn字段,如下:

 1 #!/usr/bin/env escript              %%% 和其他脚本语言一样,如果脚本未设置,将不可执行
 2 
 3 %% -*- erlang -*-
 4 %%! -smp enable -sname app-test -mnesia debug verbose            %%% erlang模拟器的参数
 5 
 6 -module('app-test').
 7 -mode(compile).                      %%%脚本语言一般都是解释性语言,而解释执行一般都比编译执行要慢,加上这一句,强制脚本编译。
 8 
9 main(AppFiles) -> %%% escript要求必须有main函数作为入口函数。 10 ConsistentRstate = lists:foldl(fun 11 (Rstate, nil) -> Rstate; 12 (Rstate, Rstate) -> Rstate; 13 (Rstate, PreviousRstate) -> 14 io:format(standard_error, "Inconsistent R-States: ~p and ~p~n", [Rstate, PreviousRstate]), 15 throw(error) 16 end, 17 nil, 18 lists:map(fun 19 (Filename) -> 20 {ok, [{application, _Application, Properties}]} = file:consult(Filename), 21 {vsn, Rstate} = lists:keyfind(vsn, 1, Properties), 22 Rstate 23 end, 24 AppFiles)), 25 io:format("~s~n", [ConsistentRstate]).
%%% appfile.appSrc 文件,是一个application文件

{application, test, [ {id,
"testId"}, {vsn, "version001"}, {modules, "&modules&"}, {mod, {sysApp, {sysAppCB, []}}}, {description, "this is a test application"}, {maxP, infinity}, % infinity | integer() {maxT, infinity}, % infinity | integer() {registered, []}, % [Name1, Name2|...] {applications, []}, % [Appl1, Appl2|...] {included_applications, []}, % [Appl1, Appl2|...] {env, []} ]}.
 1 ~/test_tmp> chmod +x app-test.escript
 2 ~/test_tmp> ./app-test.escript appfile.appSrc
 3 version001
 4   
 5 也可以这样执行.erl .beam .zip
 6 
 7 ~/test_tmp> cat test.erl
 8 -module(test).
 9 -export([main/1]).
10 
11 main([List]) ->
12   io:format("this is a test module: ~p~n", [List]).
13 
14 ~/test_tmp>
15 ~/test_tmp> escript test.erl testtest
16 this is a test module: "testtest"
17 ~/test_tmp>
18 ~/test_tmp> erlc test.erl
19 ~/test_tmp> escript test.beam testtest11
20 this is a test module: "testtest11"

以上是关于escript的简述。如有误,望指正。

原文地址:https://www.cnblogs.com/liquan2005/p/8666195.html