7

I was looking for a solution, but have not found what I need.

Script path: /dir/to/script/script.py or C:\dir\script.py

Excepted result:

$ ./script.py
output: /dir/to/script
$ cd .. && ./script/script.py
output: /dir/to/script

Is there any function in os module or something?


I mixed solutions and write:

print os.path.abspath(os.path.dirname(__file__))

But it's ugly. Is there better way?

1 Answer 1

15

os.path.realpath will give you the result:

os.path.dirname(os.path.realpath(__file__))
Sign up to request clarification or add additional context in comments.

2 Comments

the question asked for the script dirname. all realpath does is eliminate symbolic links and then return os.path.abspath
it is still fragile and assumes certain things about the cwd and where the script was executed from. for example, put os.chdir('/tmp') in the line above in the script and this solution can break.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.