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 program.py
and module.py, respectively. Run program.py and you will see ... ;-)
Thanks to both of you, Michael, Christian.
Kind regards
Andreas
program.py:
8<------------------------------------------------------------------------
#!/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
'module.whoami()':\n\n"
module.whoami()
else:
print "Hey, I was not run as a program. What's on?"
# EOF
-------------------------------------------------------------------------#
module.py
8<------------------------------------------------------------------------
# Module 'module.py'
----------------------------------------------------------#
try:
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.*********@uni-bonn.de> writes:
Hi.
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
module?
Uh, your question makes my head spin a bit, but is __file__ what you
want?
import os
os.__file__
'/usr/lib/python2.2/os.pyc'
Cheers,
mwh