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.di
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 in sys.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 containing Dev
, it should be able to find the Dev.test
module, regardless of the extra entry added to sys.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 would recommend trying out $ pip install .
in your source directory. This will install your own packages for your project.
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
sys.path.append(os.getcwd()[:os.getcwd().index('Dev')])
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. But sys.path
didn't have my current working directory. So to get around this problem, I updated my PYTHONPATH
(or you can edit sys.path
).
Setting PYTHONPATH
export PYTHONPATH=$PYTHONPATH:`pwd` (OR your project root directory)
Updating sys.path
import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')
You can use insert/append based on the order in which you want your project to be searched.
HTH.