6

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?

andrew cooke
  • 45,717
  • 10
  • 93
  • 143

2 Answers2

12

To get the absolute path of the current file:

import os
os.path.abspath(__file__)
Brian Ustas
  • 62,713
  • 3
  • 28
  • 21
  • oh! is it that simple?! there's a "free floating" `__file__`. oh! i guess that is the module's attribute. i am an idiot. you would not believe how long i spent looking for this. thanks! (can't accept for 10mins...) – andrew cooke Aug 22 '12 at 00:16
  • @andrew: it is not "free". It is an ordinary module level variable – jfs Aug 22 '12 at 01:08
  • 1
    @andrew: Please note though, that although this answers the *question*, it's not usually the correct way to do what you **want to do**. This is because the current file can be located inside a ZIP-file, in which case finding the support file that you want will fail. See JF's answer. – Lennart Regebro Aug 22 '12 at 12:01
3

To get content of external file distributed with your package you could use pkg_util.get_data()(stdlib) or pkg_resources.resouce_string() (setuptools) to support execution from zip-archives or standalone executables created by py2exe, PyInstaller or similar, example.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670