【问题标题】:executing single line commands with erl executable?使用 erl 可执行文件执行单行命令?
【发布时间】:2014-10-23 00:24:29
【问题描述】:

我想从命令行运行一些小的 Erlang 函数。

例如在 python 中打印日期,我可以使用:

python -c 'import time; print (time.strftime("%d/%m/%Y"))'

我希望能够为 Erlang 提供类似的功能:

erl -s 'date().'

但是,我收到以下错误:

Erlang/OTP 17 [erts-6.2] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

{"init terminating in do_boot",{undef,[{'date().',start,[],[]},{init,start_it,1,[]},{init,start_em,1,[]}]}}

Crash dump was written to: erl_crash.dump
init terminating in do_boot ()

是否可以从命令行运行小的 Erlang 脚本?

【问题讨论】:

    标签: shell erlang


    【解决方案1】:

    您可以使用eval 选项从命令行运行小型 Erlang 程序。例如:

    erl -noinput -eval 'io:format("hello world~n").' -s init stop
    

    您可以阅读the erl man page 了解有关命令行选项的更多详细信息,但要简短:

    • -noinput 表示运行时没有可读取的内容
    • -eval 将其参数视为 Erlang 代码文本来评估和执行
    • -s init stop 执行 the init:stop/0 function 关闭运行时

    要打印当前日期和时间,可以采取类似的方法:

    erl -noinput -eval '{{Y,Mo,D},{H,Mi,S}} = calendar:now_to_local_time(os:timestamp()),
      io:format("~4.4w-~2.2.0w-~2.2.0w ~2.2.0w:~2.2.0w:~2.2.0w~n",[Y,Mo,D,H,Mi,S]).' -s init stop
    

    此代码使用os:timestamp/0 检索当前时间,通过calendar:now_to_local_time/1 将其转换为本地时间,然后使用io:format/2 格式化结果,产生如下结果:

    2014-10-22 10:09:53
    

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 2015-05-12
      • 2013-01-09
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 2018-06-09
      • 2011-05-26
      相关资源
      最近更新 更多