简体   繁体   中英

Python/PyCharm doesn't recognize modules

I'm trying to run a python project from github I follow some suggestions about the problem like change from Python 3 to Python 2, or check if the init.py is in each folder..., but I can't solve it.

This is the error I got

Traceback (most recent call last): File "C:/Users/Pulse/Desktop/foil-python-master/src/trimlogic/test/FamilyTreeTestCase.py", line 3, in from trimlogic.test.helper import FoilTestCase ImportError: No module named trimlogic.test.helper

It doesn't matter if I run python2 or python 3, neither from console (CMD) or PyCharm

This is the structure of the project: 在此处输入图像描述

I don't know specifically what your problem is, but can maybe help you find it.

Python does module imports by path. There is a magic environment variable called PYTHONPATH that tells it where to look for modules. So when you do import trimlogic.test.helper in a python file what happens is...

It looks at PYTHONPATH and gets a list of the directories in it. It goes to the first one and looks to see if there is a trimlogic.py or a folder called trimlogic that includes the file __init__.py . If it finds a file trimlogic.py it will read it and look for a variable called test . If it is a folder, it will go into that folder and look for test.py or a folder called test with __init__.py in it. And so on. If it fails, it will check the rest of the directories in the PYTHONPATH variable the same way. Your command is failing because the src directory that contains the trimlogic folder is not on your PYTHONPATH.

There is a magic trick here. The current directory when you launch the python.exe is automatically added to the path. In a console, if you did cd C:/Users/Pulse/Desktop/foil-python-master/src and then tried running python.exe trimlogic/test/FamilyTreeTestCase.py your command would work as expected.

Further, Pycharm has some magic to help with this. First, if you right click the src directory and mark it as a sources root it will automatically run your python commands with that directory on the PYTHONPATH. You can also edit the run commands to change the working directory or the environment variables to be launched before executing commands.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM