tags:

views:

174

answers:

2

This is my Python program:

#!/usr/bin/env python

import os

BASE_PATH = os.path.dirname(__file__)
print BASE_PATH

If I run this using python myfile.py it prints an empty string. If I run it using myfile.py, it prints the correct path. Why is this? I'm using Windows Vista and Python 2.6.2.

+3  A: 

It's just a harmless windows quirk; you can compensate by using os.path.abspath(__file__), see the docs

Alex Martelli
Do I use `abspath` only if I'm on Windows or do I use it regardless?
Deniz Dogan
I'd probably use it regardless.
Jason Baker
it's not just windows
SilentGhost
I'd use it everywhere if you want the absolute path (instead of relative to current directory).
Alex Martelli
@Alex, with os.path.abspath(__file__), python -m cProfile myfile.py return "C:\Python25\lib\cProfile.py" (or "/usr/lib/python2.5/cProfile.py")...
sunqiang
@sunqiang, that's what the OP asked for, right? The absolute path to the main file (and the -m is telling Python that the main file is cProfile.py, of course).
Alex Martelli
@Alex, yes, abspath is nice for OP's question. Just met this myself last time. The script is work but Profile it surprised me.
sunqiang
@sunqiang, maybe you weren't aware that cProfile.main uses execfile on the foo.py you're passing on the commandline -- `run('execfile(%r)' % (sys.argv[0],), options.outfile, options.sort)` is the key statement, a few lines from the end of cProfile.py.
Alex Martelli
@Alex, I see, now it doesn't surprised anymore, thanks for the info.
sunqiang
A: 
os.path.normpath(os.path.join(os.getcwd(),os.path.dirname(__file__)))
tommy
read what `os.path.abspath` does.
SilentGhost