Current file (module) path

I want to know absolute current module path.
In python i could do that: os.path.abspath(__file__)
Does elixir have anything similar?

2 Likes

What exactly are you searching for?

The path to the currently executed *.exs? The path to the current modules sourcefile? The path to the current modules BEAM-file?

1 Like

__ENV__.file

See https://hexdocs.pm/elixir/Kernel.SpecialForms.html#ENV/0

5 Likes

This path is not absolute, and also it’s pointing to the source file. OP did not yet confirm if he searches for the source file or the actual BEAM.

Also using __ENV__ will print patches from the build system on the prod system, where the pointed to file might not exist at all.

1 Like

Path to the current modules sourcfile, i.e. if i call that magic function in lib/my_app.ex file, i want to get this:
/Users/my_user/my_elixir_project/lib/my_app.ex
or in case of an umbrella project:
/Users/my_user/my_elixir_project/apps/my_app/lib/my_app.ex

1 Like

I did experiment a bit, and it seems as if __ENV__.file does in fact give you the absolute and full path to the current sourcefile.

I’m wondering why you need it though… In development one is usually aware of the context and can find the file easily from the fragment thats provided in the trace. I do even think, the fragment is easier to identify than a full path. On the other hand side we have production systems, where the printed path will have nothing in common (except for the fragment that you know from devs stack traces) with the devs path, but the dev is the one who does actually fix the problems and he usually shouldn’t care about pathes used on the build or prod systems.

2 Likes

it isn’t for a stack trace. I have some resource e.g. an image in /lib/my_image.png and i have a module in lib/my_app.ex. And i want to work with that image in this module. I only know the relative path from the module to the image, it’s constant. But for this i need path to the current module. I can’t build path to the image from the root, because i don’t know where was my program run. it may run by mix then it will be the root of my app and if it’s an umbrella project it will be the project root. And also some one can run my module without mix.

4 Likes

Modules aren’t run, they are loaded.

If you process those files at compile time and do not use that path at runtime anymore, everything should be fine, but when you use the path during runtime and move the application to another computer or another path, without recompiling (eg. a distillery release) it will fail, because all pathes __ENV__.file is only valid during compilation.

If you want to integrate files into your release and load/process them at runtime use priv/-folder as briefly explained in another post:

4 Likes