在Elixir中,是否有一种方法可以直接从shell调用模块函数,而不必一定需要启动会话? 让我举个例子:
作为我的Phoenix应用程序的一部分,我编写了一个辅助模块,可以从相邻的会话中运行。 这是一个超级简化的版本:
作为我的Phoenix应用程序的一部分,我编写了一个辅助模块,可以从相邻的会话中运行。 这是一个超级简化的版本:
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
另外,我尝试将我的模块重新定义为自定义Mix任务,具体描述在此处:https://elixirschool.com/en/lessons/basics/mix-tasks/#custom-mix-task
但是这也失败了,因为我的模块依赖于一些导入/别名,例如MyApp.Repo
,并且尝试使用mix helper
或iex -S mix helper
执行文件会导致
** (ArgumentError) repo MyApp.Repo is not started, please ensure it is part of your supervision tree
如果没有其他办法,脚本只能在运行iex -S mix
的情况下成功执行,那没关系...但是如果有办法设置一条命令在shell中运行并根据需要执行此操作,那就太好了。
--no-mix-exs
作为参数传递;例如:mix run --no-mix-exs -e 'IO.puts(:hello)'
。 - Darragh Enright