views:

2279

answers:

3

Suppose I have two modules:

a.py:

import b
print __name__, __file__

b.py:

print __name__, __file__

I run the "a.py" file. This prints:

b        C:\path\to\code\b.py
__main__ C:\path\to\code\a.py

Question: how do I obtain the path to the __main__ module (a.py in this case) from within the "b.py" library?

+6  A: 

Perhaps this will do the trick:

import sys
from os import path
print path.abspath(sys.modules['__main__'].__file__)

Note that, for safety, you should check whether the __main__ module has a __file__ attribute. If it's dynamically created, or is just being run in the interactive python console, it won't have a __file__:

python
>>> import sys
>>> print sys.modules['__main__']
<module '__main__' (built-in)>
>>> print sys.modules['__main__'].__file__
AttributeError: 'module' object has no attribute '__file__'

A simple hasattr() check will do the trick to guard against scenario 2 if that's a possibility in your app.

Jarret Hardie
It does - thanks!
romkyns
Wunderbar! I'm glad I could help. If this does answer your question, would you mind hitting the 'accept' button on the question? :-)
Jarret Hardie
If you edit this to use the "import __main__" style I'll change back to accepted, as this is more detailed than the new accepted answer.
romkyns
Happy to oblige. Cheers.
Jarret Hardie
I reverted the changes... in fairness, ironfroggy gave the answer that worked best for you, and I really think he deserves sole credit.
Jarret Hardie
+11  A: 
import __main__
print __main__.__file__
ironfroggy
Neat! Important to realise that one needs to import __main__ - I made a random guess and actually tried the second line, but it failed - now I know why.
romkyns
`__main__` doesn't always have `__file__` attribute.
J.F. Sebastian
Yeah, would be nice if the answer could be updated to mention that.
romkyns
+1 because of romkyns request in the comments of the post below.
Jarret Hardie
+4  A: 

The python code below provides additional functionality, including that it works seamlessly with py2exe executables.

I use similar code to like this to find paths relative to the running script, aka __main__. as an added benefit, it works cross-platform including Windows.

import imp
import os
import sys

def main_is_frozen():
   return (hasattr(sys, "frozen") or # new py2exe
           hasattr(sys, "importers") # old py2exe
           or imp.is_frozen("__main__")) # tools/freeze

def get_main_dir():
   if main_is_frozen():
       # print 'Running from path', os.path.dirname(sys.executable)
       return os.path.dirname(sys.executable)
   return os.path.dirname(sys.argv[0])

# find path to where we are running
path_to_script=get_main_dir()

# OPTIONAL:
# add the sibling 'lib' dir to our module search path
lib_path = os.path.join(get_main_dir(), os.path.pardir, 'lib')
sys.path.insert(0, lib_path)

# OPTIONAL: 
# use info to find relative data files in 'data' subdir
datafile1 = os.path.join(get_main_dir(), 'data', 'file1')

Hopefully the above example code can provide additional insight into how to determine the path to the running script...

popcnt
If you change directory (with `os.chdir`) between launching the script and calling `os.dirname(sys.argv[0])` the result is meaningless.
RobM