Import problem
Jean-Michel Pichavant
jeanmichel at sequans.com
Wed Mar 10 07:27:33 EST 2010
News123 wrote:
> Jean-Michel Pichavant wrote:
>
>> Johny wrote:
>>
>>> I have this directory structure
>>>
>>> C:
>>> \A
>>> __init__.py
>>> amodule.py
>>>
>>> \B
>>> __init__.py
>>> bmodule.py
>>>
>>> \D
>>> __init__.py
>>> dmodule.py
>>>
>>> and I want to import bmodule.py
>>> C:\>cd \
>>>
>>> C:\>python
>>> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
>>> (Intel)] on win
>>> 32
>>> Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>>>>> from A.B import bmodule
>>>>>>
>>>>>>
>>> I am bmodule
>>> C:\>
>>>
>>> so far so good. Now I would like to import bmodule but if the current
>>> directory is \D subdirectory.
>>>
>>> C:> cd \A\B\D
>>> C:\A\B\D>
>>> C:\A\B\D>python
>>> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
>>> (Intel)] on win
>>> 32
>>> Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>>>>> import sys
>>>>>> sys.path.append('C:\\A')
>>>>>> from A.B import bmodule
>>>>>>
>>>>>>
>>> Traceback (most recent call last):
>>> File "<stdin>", line 1, in <module>
>>> ImportError: No module named A.B
>>>
>>> C:\>
>>>
>>> so I can not import a module from the parent directory? Or where did I
>>> make an error?
>>> Thanks for help
>>>
>>> L.
>>>
>>>
>> try
>>
>> import sys
>> sys.path.append('C:\\')
>> from A.B import bmodule
>>
>>
> is there any 'automatic' way of finding the top level
> directory?basically the 'top level directory is the first directory
> going upwards, that doesn't contain a __init__.py file.
>
what if some user has an __init__.py file the top level directory of
your package ?
> of course you could do this 'manually' by
> doing:
>
> # assume, that this module is A.amodule
> import sys
> import os
>
> # I'd love to have a similiar automatic construct
> if __name__ == "__main__":
> level = 1 # or function locating how far to go up before
> # finding a dir, whcih does not contain a __init__.py
> mydir = os.path.split(__file__)[0]
> topdir = os.path.join( mydir,*(("..",)*level))
> abstop = os.path.abspath(topdir)
> sys.path.append(abstop)
>
> ## now you can import with the normal module paths
>
> import A.blo
> print "and I found blo",dir(A.blo)
>
>
> bye N
>
>
>
>
You don't want to do that and you don't need it neither. That's what the
env variable PYTHONPATH is for. set it correctly, install your package
inside and everything works just fine (+standard). With a linux OS it
easy to create smb links to point to any working directory. It should be
possible on windows as well.
If your package is meant to be destributed, you may use setup.py
JM
More information about the Python-list
mailing list