debajit

debajit

Quickest way to call a function with command line arguments?

I have a module with a function that applies a transformation on a string e.g. (this is for an Advent of Code problem, where I need to do this often)

defmodule M do
  def f(some_string) do
    # apply transformation on some_string
  end
end

I need to run M.f with a string passed from the command line. What is the quickest way to do this?

Please note that

  • This script will never be deployed to production
  • I just need an easy way to call an Elixir function with some arguments from the command line

Option 1: escript

This is clean but requires some extra code (which I’d like to avoid if possible):

# mix.exs

defmodule M.Mixfile do
  def project do
    [
      ...,
      escript: escript(),
      default_task: "escript.build",
    ]
  end
 
  defp escript do
    [main_module: M.CLI]
  end
end
# in m.ex

defmodule M do
  ...
end

defmodule M.CLI do
  def main(args) do
    string = hd(args)
    IO.puts M.f(string)
  end
end

Option 2: mix run

This requires a little extra typing — I would like to move the IO.puts inside the code if possible. This approach avoids having to update mix.exs which is nice.

From the shell

%  mix run -e 'IO.puts M.f "some_user_string"'

Is there an easier / quicker way to do this?

Marked As Solved

NobbZ

NobbZ

Option 3: an *.exs

Just write an *.exs.

# foo.exs
defmodule M do
  def f(arg), do: IO.inspect arg
end

System.argv()
|> Enum.inspect(&M.f/1)

Then run it with elixir foo.exs print me

11
Post #2

Also Liked

debajit

debajit

Just for reference, I ended up using a slightly tweaked syntax:

# foo.exs
defmodule M do
  def f(arg) do
    "transformed #{arg}"
  end
end

[arg1, arg2] = System.argv
IO.puts M.f(arg1)

This allows pattern matching for the command line args, and it fails when an incorrect number of args is specified.

Where Next?

Popular in Questions Top

itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
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
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement