Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the directory where the python script is called?

Tags:

python

path

Let's say that I have a python script a.py in /A/B/a.py, and it's in the PATH environment variable. The current working directory is /X/Y/, and it's the directory where I call the /A/B/a.py.

  • In a.py, how to detect /X/Y/? I mean, how to know in which directory the python call is made?
like image 289
prosseek Avatar asked Sep 12 '10 19:09

prosseek


2 Answers

You can get the current working directory with:

os.getcwd()
like image 146
Radomir Dopieralski Avatar answered Nov 02 '22 20:11

Radomir Dopieralski


>> os.getcwd()
/X/Y
>> os.path.dirname(os.path.realpath(__file__))   # cannot be called interactively
/A/B
>> sys.path[0]
/A/B
>> os.path.abspath(sys.argv[0])
/A/B/a.py
like image 38
Matthew Rankin Avatar answered Nov 02 '22 21:11

Matthew Rankin