3

I have a program that relies on the __file__ built-in global to provide the path to data associated with the program, as in path_to_stuff = os.path.join(os.path.dirname(__file__),'stuff'). The problem is that when I run this with python -m cProfile myprog, the value of __file__ is no longer the path to myprog but rather (apparently) the path to the cProfile module, where my stuff definitely isn't.

I've read the manual and searched here and don't see anything about this. Is there a way to either (a) get cProfile to leave __file__ alone or (b) know at runtime that I'm running under cProfile so I could initialize the path with a literal string in this special case?

Edit: or, I guess, (c), is there a better way to find a dir that will always be right next to the program.py?

user405
  • 579
  • 7
  • 13

2 Answers2

0

I've found the solution for you if you still have the problem.

path_to_stuff = os.path.join(path.dirname(path.realpath(sys.argv[0])), 'stuff')
shedna
  • 1
0

(b) seems easy to do. In your program.py, check the value of __name__ . If you are running the program directly the value of __name__ would be "__main__". Instead, the value will be different if you are running it under cProfile.

Edit: I am unable to replicate your problem. cProfile doesnot seem to change either the __name__ or the __file__ value when I try it. You can also try running the profiler with in you script by calling cProfile.run()

Phani
  • 3,267
  • 4
  • 25
  • 50
  • `[21:35 ~/Dropbox/David/PPQT/scratch] cat printfile.py` `print __file__` `[21:35 ~/Dropbox/David/PPQT/scratch] python printfile.py` `printfile.py` `[21:35 ~/Dropbox/David/PPQT/scratch] python -m cProfile printfile.py` `/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/cProfile.py` `4 function calls in 0.000 CPU seconds (etc)` – user405 Mar 23 '12 at 04:37
  • Make a one-line prog printname.py `print __name__` and run it both with python and python -m cProfile and the output is the same both times. Unlike the output of `print __file__` – user405 Mar 23 '12 at 04:48
  • It is strange that the outputs are different for `__name__` and `__file__`. I ran it on Ubuntu Natty and there were no problems. – Phani Mar 23 '12 at 06:22
  • 1
    thanks for trying but I went into my Ubuntu VM (10.04 LTS) and ran my test of `print __file__` Executing `python profiletest.py` it prints `profiletest.py` but executing with `python -m cProfile profiletest.py` it prints `/usr/lib/python2.6/cProfile.py` This is exactly the same problem as in Mac OS. – user405 Mar 23 '12 at 18:15