What's the simplest way to find the path to the file in which I am "executing" some code? By this, I mean that if I have a file foo.py
that contains:
print(here())
I would like to see /some/path/foo.py
(I realise that in practice what file is "being executed" is complicated, but I think the above is well defined - a source file that contains some function that, when executed, gives the path to said file).
I have needed this in the past to make tests (that require some external file) self-contained, and I am currently wondering if it would be a useful way to locate some support files needed by a program. But I have never found a good way of doing this. The inspect module sounds like it should work, but you seem to need a class or function that is defined in that module.
In particular, the module instances contain __file__
attributes, but I can't see how to get the "current" module. Objects have a __module__
attribute, but that's the module name, not a module instance.
I guess one way is to throw and catch an exception and inspect the contents, but that seems like hard work. Surely there is a simple, easy way that I have missed?