ActiveState Code

Recipe 474083: Get the path of the currently executing python script using import.


1. sys.arg has the script name

2. Although there can be many ways, e.g. os.cwd() but, there is another

trick to

obtain the Complete URI or Location of the current script.

You can argue, os.getcwd()

import can give you working directory of the current script

Third party Java code calling your script.... ;)

#

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/local/bin/python
import pat  # touch pat.py in the cwd and try to import the empty file under Linux
import string 
import os,sys

################## os.getcwd()##############
def get_path():
	PAT=str(pat).split()[3][1:-9] # PATH extracted..
	sig=None
	try:
	 sig=os.remove(PAT + 'pat.pyc')# get_rid...
	except OSError:
	 PAT=PAT +'/'
	 sig=os.remove(PAT + 'pat.pyc')# Fix for mutiple calls..  
	return PAT
###############################
LOCATE=get_path()
print LOCATE # 
print os.getcwd()+ '/' #

print sys.argv[0] #

Comments

  1. 1. At 5:28 a.m. on 24 feb 2006, Jitender Cheema (the author) said:

    William B. good one, understood.How to do in Windows ??

  2. 2. At 7:48 a.m. on 28 feb 2006, Martin Witte said:

    Why not use sys.path[0] ? Statement 'print sys.path[0]' does what you want, see http://docs.python.org/lib/module-sys.html

  3. 3. At 8:21 a.m. on 28 feb 2006, Martin Witte said:

    addition: full path to running script. Well, to get the path + script file do something like: 'print os.path.join(sys.path[0], sys.argv[0])'

  4. 4. At 9:10 a.m. on 1 mar 2006, Jitender Cheema (the author) said:

    As I said there can be many ways, one of the way is using: sys.path[0] sys.path is List of paths.. Try this in python interpreter import sys print sys.path # prints out a whole list of python module paths.. print sys.path[0] # prints out '' Now try same as a python script and compare: import sys print sys.path # prints out a whole list of python module paths.. print sys.path[0] # prints out cwd

  5. 5. At 9:40 a.m. on 30 mar 2006, Michael Dillon said:

    The current directory can be interpreted more than one way. In order to understand what is going on with the following short section of code, put it in a file named pwd.py, then do the following:

    mkdir junk
    cd junk
    python ../pwd.py
    

    You need to make sure that your current working directory (the cd command destination) is not the same as the directory containing the Python script. After that it is self explanatory except for the .EXE path. Try running the script through PY2EXE first, and this will make more sense.

    import os,sys
    print "CWD: ",os.getcwd()
    print "Script: ",sys.argv[0]
    print ".EXE: ",os.path.dirname(sys.executable)
    print "Script dir: ", os.path.realpath(os.path.dirname(sys.argv[0]))
    pathname, scriptname = os.path.split(sys.argv[0])
    print "Relative script dir: ",pathname
    print "Script dir: ", os.path.abspath(pathname)
    
  6. 6. At 10:31 a.m. on 27 sep 2007, Daryl Spitzer said:

    sys.path[0] is not the same. Here's my (slightly) cleaned up version:

    import sys
    import os, os.path
    
    def get_my_path():
        import fake
        path = str(fake).split()[3][1:-9]
        os.remove( os.path.join( path, 'fake.pyc' ) )
        return path
    
    def do():
        print "sys.path[0]:   %s" % sys.path[0]
        print "os.getcwd():   %s" % os.getcwd()
        print "get_my_path(): %s" % get_my_path()
    <pre>
    

    Import this module from a different directory (make sure it's in your PYTHONPATH) and invoke do(). You'll see that the first two paths are the directory you're invoking from, but the third is the directory containing the module.</pre>

  7. 7. At 4:03 a.m. on 17 may 2008, Anderson Santos said:

    what about this?

    os.path.dirname(__file__)

  8. 8. At 1:45 a.m. on 6 nov 2008, Jan Vorwerk said:

    Thanks to all for your inputs.

    Just summarizing what worked best for me (I needed to get the path of the current module). It was tested on both Linux and Windows, with all the usages I could think of.

    os.path.dirname( os.path.realpath( __file__ ) )
    

    The reason for the additionnal call to os.path.realpath() is that omitting it will only work if you run the script by specifying its full path (or, under Windows, if you only type the python script name - this is because Windows has Python.exe associated to that extension and will specify the full path of the script whenever it invokes it).

    So, to import from a location relative to the current path, you can do:

    import os
    
    # BASE_PATH is the absolute path of ../.. relative to this script location
    BASE_PATH = reduce (lambda l,r: l + os.path.sep + r, os.path.dirname( os.path.realpath( __file__ ) ).split( os.path.sep )[:-2] )
    
    # add ../../scripts (relative to the file (!) and not to the CWD)
    sys.path.append( os.path.join( BASE_PATH, "scripts" ) )
    
    import foobar
    
    if __name__ == '__main__':
        ...
    

    Hope this helps!

Sign in to comment