I recently figured out how to import modules for unittesting in python. As a solution to this, I use:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from Dev.test import someclass
This works fine while running in PyCharm and I get the expected output. However, when I run from terminal I run into an error:
ImportError: No module named Dev.test
I have the init files where they are supposed to be but I'm lost as to why this is working in PyCharm but not from the terminal. I have not changed my path or anything in PyCharm as this code is supposed to be able to run with minimal modifications on other machines. Any idea as to why this is happening and what I might be able to do to fix it?
My folder structure is as follows
-Current
-Dev
-__init__.py
-test
- __init__.py
-someclass.py
-Tests
-__init__.py
-someunittest.py
I have tried running someunittest from the main folder as well as with a complete path but it only works in PyCharm
When running a script from within PyCharm, it runs it in an environment with
PYTHONPATH
set to the list of all the folders that are marked "Sources Root" (with a blue folder icon) in the project explorer.Outside of PyCharm,
PYTHONPATH
is not normally set. The first entry insys.path
refers to the current working directory where the script was run from. As long as you run your script with your terminal's working directory as the folder containingDev
, it should be able to find theDev.test
module, regardless of the extra entry added tosys.path
.Once you get the working directory correct, you should be able to remove the
sys.path
hack.I too have had this issue - and the PYTHONPATH setting set by PyCharm did seem to be the issue.
My alternative (as I was nearly finished writing the code) was to generate a setup.py - and install the classes/structure in my local virtual python environment.
Hope this helps..
I had similar problem. I think the problem is that Pycharm modifies PYTHONPATH so before running your script:
You can also create "main" python file where you set the python path and then call the other modules
I added this to my imports and it seems to have solved the problem. However, this doesn't seem like it would be the right way to do it; it will do for now.
What @codewarrior has said about the PyCharm setting its own
PYTHONPATH
is correct. Butsys.path
didn't have my current working directory. So to get around this problem, I updated myPYTHONPATH
(or you can editsys.path
).Setting
PYTHONPATH
Updating
sys.path
You can use insert/append based on the order in which you want your project to be searched.
HTH.
I would recommend trying out
$ pip install .
in your source directory. This will install your own packages for your project.