Welcome, guest | Sign In | My Account | Store | Cart

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, 21 lines
 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] #

12 comments

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

Martin Witte 18 years ago  # | flag

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

Martin Witte 18 years ago  # | flag

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])'

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

Michael Dillon 17 years, 11 months ago  # | flag

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)
Daryl Spitzer 16 years, 5 months ago  # | flag

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>

Anderson Santos 15 years, 10 months ago  # | flag

what about this?

os.path.dirname(__file__)

Jan Vorwerk 15 years, 4 months ago  # | flag

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!

Greg 14 years ago  # | flag

i get the same path info for either BASE_PATH. very clever idea - would like to make it work. if you can, please see if i missed soemthing? i created a folder one level up names scripts, and put a module in there names foo.py foo.py is just a hello world. the error is no module foo found. tia, greg

!/usr/bin/python

import os from os import path import sys

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] )

print BASE_PATH, 'original base path'

add ../../scripts (relative to the file (!) and not to the CWD)

sys.path.append( os.path.join( BASE_PATH, "../scripts/" ) )

print BASE_PATH, 'modified base path'

import foo

print someFunction()

if __name__ == '__main__': #not sure why this was in the example unless it was going to be followed by app.run() for wsgi?

Greg 14 years ago  # | flag

nvm - it says "RELATIVE PATH" but when the absolute path is used it works.

thanks :)

Naveen Kalsi 13 years, 11 months ago  # | flag

How about:

import os import sys

os.path.dirname(os.path.abspath(sys.argv[0]))

Jan Vorwerk 13 years, 7 months ago  # | flag

@Greg: not sure if you still need assistance... I confess that I did not understand your problem given the formatting issues...

@Naveen: It makes a difference if the module (python file) in which you add this recipe is not the command that you started. For instance I run module main.py in which I import 'foo' which is located elsewhere. In this foo.py using __file__ works when using sys.argv[0] does not.