1

I have the following:

% more a.py 
import os
os.system('pwd')

% python a.py 
/Users/yl/test/f

% cd ..

% python ./f/a.py 
/Users/yl/test

Basically I want the last output to be "/Users/yl/test/f", which is the path where the script is located (not where python was invoked). Have played around but didn't find a good solution. Thanks for any suggestions!

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
Hailiang Zhang
  • 17,604
  • 23
  • 71
  • 117

2 Answers2

2
import os
app_dir = os.path.dirname(__file__)
print(app_dir)
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
2
import os
print (os.path.dirname(os.path.abspath(__file__)))
ekhumoro
  • 115,249
  • 20
  • 229
  • 336