How do you properly determine the current script directory?

os.path.dirname(os.path.abspath(__file__))

is indeed the best you’re going to get.

It’s unusual to be executing a script with exec/execfile; normally you should be using the module infrastructure to load scripts. If you must use these methods, I suggest setting __file__ in the globals you pass to the script so it can read that filename.

There’s no other way to get the filename in execed code: as you note, the CWD may be in a completely different place.

Leave a Comment