相同的代码在PyCharm中不工作,但在PyCharm之外工作

thtygnil  于 11个月前  发布在  PyCharm
关注(0)|答案(2)|浏览(213)

我尝试在PyCharm中运行一个google ortools示例,得到了以下错误:

/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

字符串
然而,如果我在PyCharm之外运行相同的代码(在相应的项目venv下),它工作得很好:

(venv) edamame$ pwd
/Users/edamame/project/ortools/
(venv) edamame$ python simple_program.py 
Solution:
Objective value =  4.0
x =  1.0
y =  1.0


然后我试着在下面两种情况下打印:

import sys
print('\n'.join(sys.path))


输出:
在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


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


他们似乎是一样的,虽然.
如何让同样的代码在PyCharm中工作?

pxyaymoc

pxyaymoc1#

您在自定义ortools包和安装的包之间存在命名空间冲突。PyCharm默认将项目根(/Users/edamame/project)添加到PYTHONPATH,这导致了问题。
重命名您的自定义ortools软件包,或者在PYCharm的专用运行配置中禁用将内容根目录添加到PYTHONPATH选项。

mpbci0fu

mpbci0fu2#

环境变量PYTHONPATH是相关的。在这两种情况下,打印sys.path的值:

import sys
print('\n'.join(sys.path))

字符串
在bash中,你可能会发现输入venv然后输入$ open /Applications/PyCharm.app(或者你的Mac上的任何名称)会很有帮助。
这里是另一种方法。在pycharm中输入CMD-,(命令逗号)作为首选项,搜索Project Structure,右键单击edamame/project文件夹,然后选择alt-S Sources。这将把文件夹添加到pycharm中的路径中。同样,使用print()来验证sys.path包含的内容是否与您期望的相同。

相关问题