Elixir-从shell调用模块函数
在Elixir中,有没有一种方法可以直接从shell调用模块函数,而无需启动Elixir-从shell调用模块函数,shell,elixir,elixir-iex,Shell,Elixir,Elixir Iex,在Elixir中,有没有一种方法可以直接从shell调用模块函数,而无需启动iex-SMIX会话?让我用一个场景来说明: 作为我的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 E
iex-SMIX
会话?让我用一个场景来说明:
作为我的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-ca
关闭会话
但是,如果我尝试以下方法:
$ 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
或者,我尝试将模块重新定义为自定义混合任务,如下所述:
但这也失败了,因为我的模块依赖于一些导入/别名,如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
中成功执行,那就好了。。。但是,如果有一种方法可以将事情设置为从外壳运行一行程序以根据需要执行此操作,那就是蜜蜂的膝盖。您可以使用混合运行
和-e
参数:
$ mix run -e MyApp.Helper.start
或者,如果要将参数传递给函数:
$ mix run -e "MyApp.Helper.start(:foo, :bar)"
从混合帮助运行:
如果希望在当前脚本中执行脚本
应用程序或通过命令行标志配置应用程序
可以通过将脚本文件或eval表达式传递给
命令:
mix run my_app_script.exs arg1 arg2 arg3
mix run -e "MyApp.start" -- arg1 arg2 arg3
+1-值得补充的是,如果您想在mix项目外运行一行程序,可以将--no-mix-exs
作为参数传递;e、 g:mix-run——无混音exs-e'IO.put(:hello)