Find out the file name of a module from inside the module?

Andreas Neudecker a.neudecker at
Mon Aug 9 17:49:17 CEST 2004

Hi Michael,

sorry for making your head spin ;-)
I think, Christian's answer is exactly what I was looking for: Just cut 
out the following code snippets and put them in files called 
and, respectively. Run and you will see ... ;-)

Thanks to both of you, Michael, Christian.

Kind regards


#!/usr/bin/env python

import sys
import os

# Check if running as program
if __name__ == '__main__':
	print "I was run as a PROGRAM and my path is \n\n\t'%s'\n" % 
os.path.abspath (sys.argv[0])
	print "Now, I will call the module 'module' ..."
	import module
	print "Let's see, what 'module' says about itself, calling 

	print "Hey, I was not run as a program. What's on?"

# EOF 

# Module '' 

     THIS_FILE = __file__
except NameError:
	 print "I guess I was not called as a module. That's strange."

def whoami ():
	print "I was called as a MODULE and my path is  \n\n\t'%s'\n" % THIS_FILE

# EOF 

Michael Hudson schrieb:
> Andreas Neudecker <a.neudecker at> writes:
>>I know you can read the filename of a program as sys.argv[0]. But what
>>about modules? Is there a similar way to find out the file name of a
>>module (called by some other module or program) from inside this
> Uh, your question makes my head spin a bit, but is __file__ what you
> want?
>>>>import os
> '/usr/lib/python2.2/os.pyc'
> Cheers,
> mwh

More information about the Python-list mailing list