tags:

views:

54

answers:

2

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?
+5  A: 

You can get the current working directory with: os.getcwd()

Radomir Dopieralski
You should use `getcwdu()` for portability reasons.
Philipp
+1  A: 
>> 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
Matthew Rankin
That gives you the `/A/B` directory, the location of the `a.py`.
Radomir Dopieralski
That's not what he meant, see his question from yesterday (http://stackoverflow.com/questions/3691921/how-to-know-the-path-the-script-the-python-run).
AndiDog
@Radomir — I thought the directory where the .py file resides is what the OP wanted. Your comment made me reread the OP's question, and see that that is not the case.
Matthew Rankin