1

Possible Duplicate:
Retrieving python module path
python, path of script

I have a Python file, and I would like to parse the path when this file is executed. If I run myPython.py like this:

python ~/Documents/Project/myPython.py

I would like to know the path "~/Documents/Project/" in the file myPython.py.

Community
  • 1
  • 1
user1853170
  • 65
  • 1
  • 2
  • 8

3 Answers3

3

sys.argv[0] is the path of your script as executed by Python. You can use os.path.dirname() to get just the directory name from that:

import sys, os
print os.dirname(sys.argv[0])

It is OS-dependent if it is the full path entered on the command line; Mac OS X and Linux both include the path.

The path can, however, differ based on how Python invoked it. An alternative is to use __file__, and you can make the path absolute by using os.path.abspath() and os.path.expanduser() to cover all variations:

print os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

This example should prove helpful:

test.py:

import os

print 'Script directory: ' + os.path.realpath(os.path.dirname(__file__))
print 'Working directory: ' + os.getcwd()

Execution in terminal:

$ cd ~
$ python ~/Desktop/test.py 
Script directory: /Users/tomas/Desktop
Working directory: /Users/tomas
Hubro
  • 56,214
  • 69
  • 228
  • 381
0

Just You have to need write two statement in py file:

          import sys
          print sys.argv[0] 
Anup
  • 200
  • 1
  • 13