I have some code that loads a default configuration file and then allows users to supply their own Python files as additional supplemental configuration or overrides of the defaults:
# foo.py
def load(cfg_path=None):
# load default configuration
exec(default_config)
# load user-specific configuration
if cfg_path:
execfile(cfg_path)
There is a problem, though: execfile()
executes directives in the file specified by cfg_path
as if it were in the working directory of foo.py
, not its own working directory. Thus, import
directives might fail if the cfg_path
file does, say, from m import x
where m
is a module in the same directory as cfg_path
.
How do I execfile()
from the working directory of its argument, or otherwise achieve an equivalent result? Also, I've been told that execfile
is deprecated in Python 3 and that I should be using exec
, so if there's a better way that I should be doing this, I'm all ears.
Note: I don't think solutions which merely change the working directory are correct. That won't put those modules on the interpreter's module-lookup path, as far as I can tell.
execfile()
appears to be launching an entirely new process with its own working directory, which isn't the same as the one I'm launching from. – Conciliatory