smon

smon

What is the correct way to pass command line options?

I tried something like this in my mix.exs:

def application do
  [
    applications: [:logger, :httpoison, :poison],
    mod: {Test, []}
  ]
end

In my Test.ex:

defmodule Test do
  use Application

  def start(_mode, _args) do
    System.argv
    |> Test.CLI.main
  end
end

But how do I pass arguments to the start function without “confusing” the mix run script? If I try to mix run --type marc, I get

** (Mix) Could not invoke task "run": 1 error found! --type : Unknown option

Ok, I kind of get that. But then I noticed that if I add some random argument in between like mix run what --type marc, it kind of works: The what gets lost on the way, meaning it is missing from System.argv, which leaves ["--type", "marc"].

You may have noticed: I am somewhat confused. :wink:

What is the correct way to do this besides turning to escript?

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

It sounds like you want a mix task or an escript.

Also Liked

sger

sger

Hello,

You need escript for this job for example in your mix.exs you must pass

escript: [main_module: MyApp]

then in your module define something like this:

defmodule MyApp do
 def main(args) do
  args |> parse_args |> process
 end

def process([]) do
 IO.puts "No arguments given"
end

def process(options) do
 IO.puts "Hello #{options[:name]}"
end

 defp parse_args(args) do
  {options, _, _} = OptionParser.parse(args, switches: [name: :string])
  options
 end
end

finally from the command line:

mix escript.build
$ ./my_app --name=Elixir
Oliver

Oliver

Hello.

I was looking for a thread similar to my original post which I can no longer reply to (Google group got closed): https://groups.google.com/forum/#!topic/elixir-lang-talk/EbVag1bErEk

My original solution was indeed based on escript, but in order to enable “-mode embedded” for code preloading I had to switch away from it and over to building my software with distillery.

distillery builds you scripts to start your application like this: bin/myapp foreground

There is no escript involved.

And I found a solution for commandline arguments: http://erlang.org/doc/man/init.html#get_plain_arguments-0

I filtered, joined, and processed the results and I had all the commandline arguments I needed. Finally solved my problem with commandline arguments.

My final commandline looks like this: bin/myapp foreground --config "something". (You have other options to start the application, of course, like detached or with an attached console.) I then put the parsed results in my applications environment with Application.put_env(:myapp, <key, <value>) and retrieve them later when needed easily.

smon

smon

My idea was to avoid the mix escript.build step. Looking at mix tasks, it seems like I would have to start all dependencies manually - so maybe an escript is still the more elegant solution. Thank you for your example!

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement