【问题标题】:Elixir - call a module function from the shellElixir - 从 shell 调用模块函数
【发布时间】:2018-09-14 07:20:15
【问题描述】:

在 Elixir 中,有没有办法直接从 shell 调用模块函数,而不必启动 iex -S mix 会话?让我用一个场景来说明:

作为我的 Phoenix 应用程序的一部分,我编写了一个帮助模块,该模块将从相邻的 iex -S mix 会话中运行。这是一个超级简化的版本:

defmodule MyApp.Helper do
  # For the demo, these imports/aliases are not used - but they're there in real life.
  import Ecto.Query
  alias MyApp.Repo

  def start do
    {:ok, "Done"}
  end
end

如果我使用iex -S mix 开始会话,然后从模块中运行一个函数,一切正常:

$ iex -S mix
Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Compiling 2 files (.ex)
Interactive Elixir (1.5.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> MyApp.Helper.start
{:ok, "Done"}

然后ctrl-c a 关闭会话。

但是,如果我尝试类似:

$ iex -S mix MyApp.Helper.start

结果

Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Compiling 2 files (.ex)
** (Mix) The task "MyApp.Helper.start" could not be found

或者,我尝试将我的模块重新定义为自定义混合任务,如下所述:https://elixirschool.com/en/lessons/basics/mix-tasks/#custom-mix-task

但这也失败了,因为我的模块依赖于一些导入/别名,例如MyApp.Repo,并且尝试使用mix helperiex -S mix helper 执行文件导致

** (ArgumentError) repo MyApp.Repo is not started, please ensure it is part of your supervision tree

如果没有办法解决这个问题并且脚本只能从正在运行的iex -S mix 中成功执行,那很好......但是如果有一种方法可以设置,那么单线可以从 shell 运行要让它根据需要执行,那就是蜜蜂的膝盖。

【问题讨论】:

    标签: shell elixir elixir-iex


    【解决方案1】:

    您可以将mix run-e 参数一起使用:

    $ mix run -e MyApp.Helper.start
    

    或者如果您有要传递给函数的参数:

    $ mix run -e "MyApp.Helper.start(:foo, :bar)"
    

    来自mix help run

    如果希望在当前执行脚本 应用程序或通过命令行标志配置应用程序,它是 可以通过将脚本文件或 eval 表达式传递给 命令:

    mix run my_app_script.exs arg1 arg2 arg3
    mix run -e "MyApp.start" -- arg1 arg2 arg3
    

    【讨论】:

    • +1 — 值得补充的是,如果您想在混音项目之外运行单线,您可以将 --no-mix-exs 作为参数传递;例如:mix run --no-mix-exs -e 'IO.puts(:hello)'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 2018-01-28
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多