2

I have a Python script that I run as part of an Elixir library that I am writing - that is, upon starting the application, I run System.cmd("python", [path/to/script], []) in one of my start_link functions.

I install the script in the user's deps/mylibrary/lib folder.

The path/to/script is the part that I don't know how to do - I can deduce where the script is located by evaluating System.cwd() and looking at the result, but this seems wrong.

I figure there must be a way to do this using Mix.

MaxStrange
  • 137
  • 1
  • 10
  • I usually use `Path.expand` with `__DIR__` to get a path relative to the current source file, e.g. `Path.expand("path/to/script", __DIR__)`. Could you see if this works for you? (You'll probably have to do `../path/to/script` or `../../path/to/script` depending on which file you're calling this from.) – Dogbert Apr 15 '17 at 05:13
  • @Dogbert Yes, that works! But I was wondering also if this is the canonical way of doing it. Seems like many Elixir libraries must have non-Elixir dependencies. Are these usually installed in deps/whatever/lib like I've done? – MaxStrange Apr 15 '17 at 06:13
  • 1
    I believe files you want to access at runtime should be put in the `priv/` folder and then you can be sure you can access them from your code using `:code.priv_dir(:my_package)`. See http://stackoverflow.com/questions/43414104/read-files-in-phoenix-in-production-mode and my comment there. – Dogbert Apr 15 '17 at 06:56
  • @Dogbert Yeah, that works. I guess that's probably the way to do it. If you want to write an answer, I'll accept it. Thanks! – MaxStrange Apr 15 '17 at 19:19

1 Answers1

6

Files that are needed by a library/package at runtime should be stored in the priv/ folder. Everything in this directory will be present in Erlang Releases created by e.g. Distillery. At runtime, you can use the path returned by :code.priv_dir/1 to know the location of the priv directory of the package.

So, if your Python script is in priv/foo/bar.py, you can get the absolute path of that file using:

Path.join(:code.priv_dir(:my_package), "foo/bar.py")

where :my_package is the name of your package.

Dogbert
  • 212,659
  • 41
  • 396
  • 397