miti.sh/docs/2023-09-15-open-an-iex-shell-from-an-elixir-script.md

2.0 KiB

{ id: "open-an-iex-shell-from-an-elixir-script" title: "Open An IEx Shell From An Elixir Script" blurb: "We can run an Elixir script with either the elixir or the iex command. Both will execute the code, but the second command opens an interactive IEx shell afterward. What if, we won't know until runtime whether we want a shell or not? How can we start an IEx session even when we use elixir, instead of iex, to run our script?" }


title: "Open An IEx Shell From An Elixir Script" blurb: "We can run an Elixir script with either the elixir or the iex command. Both will execute the code, but the second command opens an interactive IEx shell afterward. What if, we won't know until runtime whether we want a shell or not? How can we start an IEx session even when we use elixir, instead of iex, to run our script?" ...

Method 1

Here's a quick test script:

`run.exs`

:shell.start_interactive({IEx, :start, []})

System.no_halt(true)

System.no_halt(true) is needed so that the interactive session doesn't die when the process running the script ends. You could also use the elixir command with the --no-halt option instead to achieve the same effect.

When we run this script with just elixir (instead of iex), we should still see an interactive IEx session start.

$ elixir run.exs
Erlang/OTP 26 [erts-14.1] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1] [jit:ns]

Interactive Elixir (1.15.6) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>

Method 2

While researching, I found another way that works, but it's even more obscure than the above method.

:user_drv.start_shell(%{initial_shell: {IEx, :start, []}})

I can't find documentation for user_drv, I had to browse the code directly.