$MAIN_DIR expands to the location of the main python file that is invoked. So if you run it like “python main.py”, then $MAIN_DIR is the directory containing main.py.
I use the following code to open files in the same directory as the model:
def GetDirPath(self, name='hull'):
"""Returns the directory path the model was loaded from."""
return self.part[name].node().getFullpath().getDirname();
sys.path[0] will only work in a limited number of environments, that excludes the .p3d environment. It’s much more reliable to use os.path.dirname(sys.argv[0]).
(Furthermore, using forward slashes won’t work on Windows, so you’ll either have to use os.path.join or use Panda’s path mechanism.)
But it’s even more reliable to use ExecutionEnvironment.getEnvironmentVariable(“MAIN_DIR”),or load models like this:
loader.loadModel("$MAIN_DIR/models/blah")
$MAIN_DIR is automatically set to the location of the main.py file by Panda3D.
If you want to use it for a non-Panda function, you can always use:
from panda3d.core import ExecutionEnvironment as EE
f = Filename(EE.expandString("$MAIN_DIR/etc/some_file"))
handle = open(f.toOsSpecific(), 'r')