Absolute imports?
Roy Smith
roy at panix.com
Sat Jan 8 17:45:23 EST 2011
In article <877heff4fl.fsf at benfinney.id.au>,
Ben Finney <ben+python at benfinney.id.au> wrote:
> Roy Smith <roy at panix.com> writes:
>
> > If I have an absolute path to a file (i.e. '/home/roy/foo.py'), is
> > there a way to import that as a module WITHOUT modifying sys.path? I'm
> > using Python 2.6.
>
> Importing a module with ‘import’ is done by using the module's name,
> which is only *incidentally* related to its filesystem path.
>
> What is the problem you're trying to solve? It is likely we can suggest
> a better solution.
Well, the problem I'm trying to solve is that I have an absolute
pathname to a python source file that I want to import as a module :-)
I'm working on a project where developers will typically have several
sandboxes, with different versions of the code. There's a config file
(which I have no control over) which defines a big multi-level dict
containing configuration options:
config = {
'memcache_servers' : ['localhost'],
'build_type' : 'development',
'thrift_configs' : {
'SearchService' : {'hosts' : ['localhost'],
'sendTimeout' : 300,
'port' : 9192,
'recvTimeout' : 3000
},
}
}
and so on. The file is auto-generated by some huge pile of perl scripts
which also generates the same information in a forms ingestible by perl,
PHP, Java, shell scripts, etc. Not how I would have designed it, but it
is what it is.
The best I can describe how to find the location of the config file is,
"Work your way up the directory tree from where you are now, (i.e.
following '..' links) until you get to the top level of the project,
then from there, it's ./code/configs/autogen/config.py."
It's reasonably straight-forward to figure out that absolute path,
starting from sys.argv[0] and using the tools in os.path. Now I need to
import the file, given that I know its absolute pathname. It looks like
imp.load_source() does what I want, I'm just wondering if there's a
cleaner way.
More information about the Python-list
mailing list