472,780 Members | 1,983 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,780 software developers and data experts.

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

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?

Kind regards
Andreas

Jul 18 '05 #1
4 1774
Andreas Neudecker wrote:
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?


If your modules knows that it is a module, it can inspect its
__file__ attribute.
You can find out whether you have been imported by testing
whether there is a __file__ attribute, otherwise you are
probably executed, and there is no name available.

try:
fname = __file__
except NameError:
fname = "?"

In cases where you absolutely need a file name, and if you know
that you are also used as a module, you can of course import
yourself, in order to get the file name. This implies the need
to know your module name, which doesn't make things so much better:

# assuming this is MyModule
import MyModule
fname = MyModule.__file__
del MyModule

Or even shorter:

from MyModule import __file__ as fname

ciao - chris
--
Christian Tismer :^) <mailto:ti****@stackless.com>
Mission Impossible 5oftware : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/

Jul 18 '05 #2
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

--
Of the four project development variables - scope, cost, time and
quality - quality isn't really a free variable. The only possible
values are "excellent" and "insanely excellent", depending on
whether lives are at stake. -- Kent Beck, XP Explained
Jul 18 '05 #3
Danke, Christian! Hat mir sehr geholfen! :-)
Gruß
Andreas
Christian Tismer schrieb:
Andreas Neudecker wrote:
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?

If your modules knows that it is a module, it can inspect its
__file__ attribute.
You can find out whether you have been imported by testing
whether there is a __file__ attribute, otherwise you are
probably executed, and there is no name available.

try:
fname = __file__
except NameError:
fname = "?"

In cases where you absolutely need a file name, and if you know
that you are also used as a module, you can of course import
yourself, in order to get the file name. This implies the need
to know your module name, which doesn't make things so much better:

# assuming this is MyModule
import MyModule
fname = MyModule.__file__
del MyModule

Or even shorter:

from MyModule import __file__ as fname

ciao - chris

Jul 18 '05 #4
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

Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: rh0dium | last post by:
Hi all, Basically I have a bunch of pluggins in a directory (METDIR). For each one of these templated pluggins I want to do a specific routine. Let's start with a basic template file...
1
by: TRI_CODER | last post by:
I am trying to solve the following exception. The exception occurs when my ASP.NET code behind code attemtps to access a remore site using SSL. Please note that all certificates are valid and the...
5
by: Tim Eliot | last post by:
Just wondering if anyone has hit the following issue and how you might have sorted it out. I am using the command: DoCmd.TransferText acExportMerge, , stDataSource, stFileName, True after...
2
by: John Regan | last post by:
Hello All I am trying to find the owner of a file or folder on our network (Windows 2000 Server) using VB.Net and/or API. so I can search for Folders that don't follow our company's specified...
13
by: bobueland | last post by:
I'm a newbie experimenting with Python. I want to incrementally develop a module called 'circle'. The problem is now that the file name is used for two purposes. To keep track of the version number...
10
by: Ben Finney | last post by:
Howdy all, Question: I have Python modules named without '.py' as the extension, and I'd like to be able to import them. How can I do that? Background: On Unix, I write programs intended to...
5
by: PaulS | last post by:
new to Fedora7, typed python in interactive interpreter, then help(). Then modules to get a list of modules. Then module name to get info on a module but no help file. What is the help file...
4
by: Frank Aune | last post by:
Hello, I've been playing with the python logging module lately, and I manage to log to both stderr and MySQL database. What I'm wondering, is if its possible to specify the database handler in...
8
by: inFocus | last post by:
Hello, I am new to python and wanted to write something for myself where after inputing two words it would search entire drive and when finding both names in files name would either copy or move...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.