【问题标题】:Get return value in shell from external erlang file从外部erlang文件获取shell中的返回值
【发布时间】:2012-05-15 10:10:52
【问题描述】:

我在 erlang 中有一个启动一些模块的脚本文件。在 erlang shell 中,我想使用 start 函数返回的对象。

我有我的文件:

-module(myfile).
main() ->
    %% do some operations
    MyReturnVar.

我想为最终用户提供最简单的方法来操作MyReturnVar 变量。在 shell 脚本中,我执行$ erl -s myfile main,它在 shell 中执行函数。

有没有办法在 shell 中获取 MyReturnVar ?

另一种方法是直接从shell加载模块

$ erl
1> X = myfile:main().

但我不太喜欢这个解决方案,我想要更多“一个命令”选项(或者我可以在 shell 脚本中连续执行多个命令)。

谢谢

【问题讨论】:

    标签: shell erlang


    【解决方案1】:

    当您连续说几个时,听起来您想将一个命令的结果通过管道传递给另一个命令。为此,您不使用只能是 int 的返回值,而是使用标准输入和标准输出。这意味着您想要将MyReturnVar 打印到标准输出。为此,您有 io:format。根据MyReturnVar 的值类型,您会执行以下操作:

    -module(myfile).
    main() ->
        %% do some operations
        io:format("~w", [MyReturnVar]),
        MyReturnVar.
    

    现在您应该能够将命令的结果通过管道传输到其他进程。例如:

    $ erl -s myfile main | cat
    

    【讨论】:

    • 不,这个想法不是在终端中显示结果,而是对用户说“只需执行脚本run.sh,然后您将进入带有所需变量的erlang shell”。我希望能够使用这些变量执行其他 erlang 操作。我只是想知道除了X = myfile:main() 操作之外还有另一种方法。
    【解决方案2】:

    您可以(ab)使用.erlang 文件来实现此目的(请参阅erl(1) 手册页)。或者在erlang-history .

    【讨论】:

      【解决方案3】:

      尽可能使用 escript。

      $cat test.escript
      #!/usr/local/bin/escript 
      main([]) ->
              MyReturnVar=1,
              io:format("~w", [MyReturnVar]),
              halt(MyReturnVar).
      $escript test.escript 
      1
      $echo $?
      1
      

      这将打印出 MyReturnVar 并返回 MyReturnVar,这样您就可以使用管道或只捕获 $?来自 shell 脚本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-24
        • 2014-01-08
        • 1970-01-01
        • 1970-01-01
        • 2017-09-08
        • 1970-01-01
        • 2014-12-31
        相关资源
        最近更新 更多