erlang的脚本执行---escript

本文介绍Erlang语言中的escript工具,该工具允许开发者直接从命令行运行Erlang脚本而无需编译。通过示例展示了如何使用escript解析application配置文件并提取版本信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值