Reputation: 25366
I am trying to run a google ortools example in PyCharm and got the following errors:
/Users/edamame/project/ortools/simple_program.py
Traceback (most recent call last):
File "/Users/edamame/project/ortools/simple_program.py", line 3, in <module>
from ortools.linear_solver import pywraplp
ModuleNotFoundError: No module named 'ortools.linear_solver'
Process finished with exit code 1
However, if I run the same code outside the PyCharm (under the corresponding project venv), it works fine:
(venv) edamame$ pwd
/Users/edamame/project/ortools/
(venv) edamame$ python simple_program.py
Solution:
Objective value = 4.0
x = 1.0
y = 1.0
I then tried to print below in both cases:
import sys
print('\n'.join(sys.path))
The outputs:
In PyCharm:
/Users/edamame/project/venv/bin/python
/Users/edamame/project/ortools/so_example.py
/Users/edamame/project/ortools
/Users/edamame/project
/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload
/Users/edamame/project/venv/lib/python3.6/site-packages
/Users/edamame/project/venv/lib/python3.6/site-packages/setuptools-39.1.0-py3.6.egg
/Users/edamame/project/venv/lib/python3.6/site-packages/pip-10.0.1-py3.6.egg
Outside PyCharm:
(venv) edamame$ python so_example.py
/Users/edamame/project/ortools
/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload
/Users/edamame/project/venv/lib/python3.6/site-packages
/Users/edamame/project/venv/lib/python3.6/site-packages/setuptools-39.1.0-py3.6.egg
/Users/edamame/project/venv/lib/python3.6/site-packages/pip-10.0.1-py3.6.egg
They seem to be the same though ... not sure what could be the problem ...
How do I make the same code working in PyCharm?
Upvotes: 0
Views: 445
Reputation: 8495
You have a namespace collision between custom ortools
package and the installed one. PyCharm adds the project root (/Users/edamame/project
) to PYTHONPATH
by default and it causes the problem.
Either rename your custom ortools
package or disable Add content roots to PYTHONPATH option in the dedicated Run Configuration in PYCharm.
Upvotes: 1
Reputation: 20425
The env var PYTHONPATH is relevant. In both situations, print the value of sys.path
:
import sys
print('\n'.join(sys.path))
In bash, you may find it helpful to enter the venv and then $ open /Applications/PyCharm.app
(or whatever it's called on your Mac). Then the running pycharm will inherit PYTHONPATH from bash.
Here is another approach. Within pycharm type CMD-, (command comma) for preferences, search for Project Structure, right click on the edamame/project folder, and choose alt-S Sources. This will add the folder to your path within pycharm. Again, use print()
to verify sys.path
contains what you expect it to contain.
Upvotes: 1