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?

4

2 回答 2

0

(b) 似乎很容易做到。在您的 program.py 中,检查__name__. 如果您直接运行程序,则 的__name__值为"__main__"。相反,如果您在 cProfile 下运行它,则该值会有所不同。

编辑:我无法复制您的问题。当我尝试它时,cProfile 似乎没有改变__name__或值。__file__您还可以尝试通过调用在脚本中运行探查器cProfile.run()

于 2012-03-23T02:48:55.300 回答
0

如果您仍然有问题,我已经为您找到了解决方案。

path_to_stuff = os.path.join(path.dirname(path.realpath(sys.argv[0])), 'stuff')
于 2014-01-23T09:56:39.400 回答