Python: Knowing the path of the currently running script

Problem Statement:

When we deal with frameworks, how often do we have to import modules. And it doesn’t stop there; there arises a need where the imported would in turn import an another module, right? Would debugging an error condition be easy in these cases. If you have dealt with frameworks before, you would definitely understand the complexity of finding the fault location (exact module where the fault lies). Often people using logging mechanisms where they print to a file and start debugging. Wouldn’t it be simple if we have a single line of code, just to tell which module is currently running? Was the first module being run when error occurred or was it the second module?


Solution to this problem is fairly simple. Use of __file__ attribute in python.

__file__ attribute gets you information on the currently running script/module. Let’s demonstrate this with an example. Consider, we have a parent script which imports a module called Codes would like these:

import Module

from Module import method

print "We're in %r" %__file__


def method():

	import os

	f = open("C:\\sample.txt", "w")

	f.write('This is a sample file')

	print "We're in %r" %__file__


	os.system("del C:\\sample.txt")

Now, if we run the parent script, on command prompt, the output that we get is:



We’re in ‘C:\\Python26\\’
We’re in ‘C:\\Python26\\’

When the was running, __file__ gave us the path of current running script, but when the was imported and then __file__ was used, it gave the path of the module, and not the path of the parent script.


– We can easily find the path of the current running script.

– Also we can easily find out which module is currently being run. This helps in easy debugging.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s