How to run a binary from Elixir code?

I have the latest version of yt-dlp in the same folder as my test.exs file.


I want to run yt-dlp with some params.

System.cmd("yt-dlp", [])

** (ErlangError) Erlang error: :enoent
    (elixir 1.13.0) lib/system.ex:1044: System.cmd("yt-dlp", [], [])
    (elixir 1.13.0) lib/code.ex:1183: Code.require_file/2

How can I run this command from within Elixir?


I also tried to set it as an environment variable and invoke that env var instead of the binary.

export yt_dlp="/home/sergio/Work/ekeko/yt-dlp"

System.cmd("yt_dlp", [])
** (ErlangError) Erlang error: :enoent
    (elixir 1.13.0) lib/system.ex:1044: System.cmd("yt_dlp", [], [])
    (elixir 1.13.0) lib/code.ex:1183: Code.require_file/2


An absolute path worked.

System.cmd("/home/sergio/Work/ekeko/yt-dlp", [""])
1 Like

The System.cmd function looks for the binary to execute in the PATH environment variable.

If you don’t want to specify the full path every time, you can just add the current folder to PATH:

# Prepend your dir to PATH
path = System.get_env("PATH")
System.put_env("PATH", "#{__DIR__}:#{path}")

# Then use your command
System.cmd("yt-dlp", [""])

Had a quick look at System.cmd/3 and found this:

:cd - the directory to run the command in

So if you don’t want to change your environment variables, you can do this:

System.cmd("yt-dlp", [""], cd: __DIR__)

(not tested :smile:)

1 Like

cd only change the “the directory to run the command in”, not the PATH env so it won’t work.

System.cmd/2 uses :os.find_executable/1 to find the binary:

find_executable/1 uses the current execution path (that is, the environment variable PATH on Unix and Windows).