Importing a file (not a module).
Steve Holden
steve at holdenweb.com
Sun Feb 8 23:24:51 EST 2009
Luis Zarrabeitia wrote:
> Is there any way to "import" a .py file that is not on sys.path?
> I'd like to 'import' a file that resides somewhere on my filesystem without
> having to add it's directory to sys.path. At first, I thought that something like
>
> my_module = __import__("path/to/file")
>
> would work, but I was mistaken. Ideally, the path would be specified as a
> relative path from the importer's module, and not from the CWD (that's another
> question, I guess).
>
> Related question: how could I change the sys.path for this_script.py without
> changing it much? I'd like to have this_script a few more directories on its
> pythonpath, but I don't want to clutter the begining of the script with
> "sys.path.append(...)"s, specially because I need to do that for several
> scripts. I thought of creating a modify_pythonpath.py and import it from all of
> them, but I don't want to keep that script on the global python path nor on any
> of the project folders (it is required by more than one).
>
> Currently I have a symlink from the original modify_pythonpath.py to each
> project directory, but that seems clumsy.
>
Take a look at the imp module:
>>> import imp
>>> m = imp.load_source("mymodule", "doors.px")
['G', 'G', 'G'] [1, 1] [1, 1, 1]
['G', 'G', 'C'] [1, 1] [1, 1]
['G', 'C', 'G'] [1] [1, 1]
['G', 'C', 'C'] [1] [1]
['C', 'G', 'G'] [1] [1, 1]
['C', 'G', 'C'] [1] [1]
['C', 'C', 'G'] [] [1]
['C', 'C', 'C'] [] []
>>> m
<module 'mymodule' from 'doors.px'>
>>> import sys
>>> sys.modules['mymodule']
<module 'mymodule' from 'doors.px'>
>>>
As you can see it works with non-standarde xtensions too.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list