How to get __main__ module filename in Python?

Suppose I have two modules:

a.py:

import b print __name__, __file__ 

b.py:

 print __name__, __file__ 

I ran the file "a.py". It means:

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

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

+45
python python-module
Mar 03 '09 at 14:24
source share
5 answers
 import __main__ print __main__.__file__ 
+57
Mar 03 '09 at 16:04
source share

Perhaps this will be a trick:

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

Note that for security, you should check if the __main__ module has the __file__ attribute. If it is dynamically created or just launched in the python interactive console, it will not have __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 check hasattr () will do the trick to protect against scenario 2, if possible in your application.

+26
Mar 03 '09 at 14:27
source share

The following Python code provides additional functionality, including the fact that it works easily with py2exe executables.

I use similar code for this to find paths relative to running the 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') 

Hope the above sample code can give an additional idea on how to determine the path to the running script ...

+14
Mar 03 '09 at 20:29
source share

Another method would be to use sys.argv[0] .

 import os import sys main_file = os.path.realpath(sys.argv[0]) if sys.argv[0] else None 

sys.argv[0] will be an empty string if Python starts with -c or if it is installed from the Python console.

+5
Apr 05 '14 at 18:08
source share
 import sys, os def getExecPath(): try: sFile = os.path.abspath(sys.modules['__main__'].__file__) except: sFile = sys.executable return os.path.dirname(sFile) 

This feature will work for compiled Python and Cython programs.

+1
Jan 17 '13 at 20:57
source share



All Articles