There's potentially 2 sources of error. The first, like @TomCho has already pointed out is if the __init__.py
file is not properly in your modules. However, since it works in PyCharm, I'm guessing it's the second.
The second is if your PYTHONPATH
variable is not set up properly. There are a number of places which python will by default look for modules. This includes places like the Python install directory and the current working directory. To view a full list of places which Python looks, do..
import sys
print(sys.path)
Python will then descend into each directory that has a __init__.py
file, which is what makes that file so important. However, most likely you are not putting your code into the default places Python looks. And that's the whole purpose of the PYTHONPATH
environment variable. You make it a list of paths where your packages are, and then those will be added to the sys.path
seen above.
By default, PyCharm
will add your project directory to the PYTHONPATH
, which is why I'm guessing it worked in PyCharm, but not on the command line.
To set PYTHONPATH
in Linux, go to the command line and type
export PYTHONPATH=/path/to/python/module
If you have more than one path you need to add, you can keep appending with :
so the more general case is
export PYTHONPATH=$PYTHONPATH:/path/to/python/module
And you can keep doing that. I typically add that line to my ~/.bashrc
file.
If you are in windows, modifying environment variables is different, but it's still pretty easy.