5

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.

Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
Deniz Dogan
  • 25,711
  • 35
  • 110
  • 162

3 Answers3

8

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

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • Do I use `abspath` only if I'm on Windows or do I use it regardless? – Deniz Dogan Sep 27 '09 at 16:04
  • I'd probably use it regardless. – Jason Baker Sep 27 '09 at 16:06
  • I'd use it everywhere if you want the absolute path (instead of relative to current directory). – Alex Martelli Sep 27 '09 at 16:14
  • @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 Sep 27 '09 at 16:42
  • @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 Sep 27 '09 at 17:01
  • @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 Sep 27 '09 at 17:08
  • @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 Sep 27 '09 at 17:32
  • @Alex, I see, now it doesn't surprised anymore, thanks for the info. – sunqiang Sep 27 '09 at 17:50
0
os.path.normpath(os.path.join(os.getcwd(),os.path.dirname(__file__)))
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
tommy
  • 1
0

In many cases it's better to use:

os.path.dirname(sys.argv[0])
KamilD
  • 163
  • 1
  • 7