Fail python import from another folder

2019-06-21 19:14发布

问题:

I am experimenting with python, mostly troubleshooting other people's code. I am trying to get a program to run, "path\folderA\program.py".

I am running the program from path\folderA

I am getting an error:

ImportError: No module named fff.ggg.ppp

program.py contains an import:

from fff.ggg.ppp import mmm

In the folder "path\folderB" there are: "path\folderB\fff\__init__.py" "path\folderB\fff\ggg"

folder ggg also contains __init__.py, as well as program ppp.py

From reading other posts, like Python error "ImportError: No module named" I understand that having the __init__.py makes a folder a "package" which makes imports from it possible - but it doesn't work, since I am getting an error.

This has been working for other people that worked with these projects, so there is something wrong with my setup.

I read something about the directories having to be in the sys.path. Does that mean I have to add them to the environment variable path ? That would mean adding a lot of directories to the PATH though, so it can't be.

So I also found the following:

import sys
sys.path.append( <path to FolderB> )

But that means changing the code (which has not been necessary for other people) and hard-coding a path to what it is on my local machine - which I shouldn't have to, right ?

I can't visualize it - apparently I am not supposed to change the code and hard-code the physical path to the import module - so how can a program from folderA even know to look in folderB for an import ?

How does the magic of __init__.py work ?

回答1:

I can't visualize it - apparently I am not supposed to change the code and hard-code the physical path to the import module - so how can a program from folderA even know to look in folderB for an import ?

You are correct. Somehow you have to tell python to look for imported modules in folderB. There is no __init__.py magic that lets you import from other folders on your hard drive.

Usually, if you've got various different python packages like that, they work by being installed into python's library. That way they can imported from anywhere. This is usually accomplished by a setup.py script. Check if folderB has one. Run it with python setup.py install.

If that doesn't work, we'll need more information about how this code is structured.



回答2:

Folder B must be on the sys.path, so you would either need to move mmm to A, or modify sys.path from within A (not sure if that works). __init__.py tells python that the folder is a package, so you could have folders with __init__.py within folders with __init__.py and python treats the folders inside as parts of the parent folder. Check out sympy or almost any large python library and you will find such a structure. It can also contain code to be run on import, but can also be empty.



标签: python import