Please explain why os.path.dirname(__file__)
is working in Django, but not working in python?
This is kind of weird situation which I can't understand.
I made a python script and put it in a file test_file.py:
import os
dirname = os.path.dirname(os.path.dirname(__file__))
realpath = os.path.dirname(os.path.realpath(__file__))
abspath = os.path.dirname(os.path.abspath(__file__))
print dirname
print realpath
print abspath
When I run the script, I get results:
(env)user@ubuntubox:~/srv/django_pro$ python test_file.py
/home/srv/django_pro
/home/srv/django_pro
(env)user@ubuntubox:~/srv/django_pro$
I get results that realpath and abspath are working, but dirname is empty. However in Django settings.py I have:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
If I go into python shell and print out BASE_DIR, it is not empty:
(env)user@ubuntubox:~/srv/django_pro$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.conf import settings
>>>
>>> print 'BASE_DIR:\n%s' % settings.BASE_DIR
BASE_DIR:
/home/srv/django_pro
>>>
And that means os.path.dirname(os.path.dirname(file)) is not empty. I am using same python in both cases. And my Django version is:
Django==1.7b4
So what is the trick?
The first script that you run has __file__
set to the path you passed to Python. You started the script with python test_file.py
so __file__
is set to 'test_file.py'
. Had you used python /home/srv/django_pro/test_file.py
your test script would have shown a path for all three options.
Imported modules, on the other hand, have their __file__
value set to the full path.
You need to take this into account and always use os.path.abspath
:
directory = os.path.dirname(os.path.abspath(__file__))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With