为了解释答案,我重新创建了您的项目结构
/projectRoot/
folder1/
somecode.py
utils/
__init__.py
myutils1.py
一些代码.py
from utils.myutils1 import myclass
if __name__ == "__main__":
print(myclass)
myutils1.py
myclass="tarun"
从 pycharm 运行它们没有任何问题,但从终端运行它们将产生以下错误
File "somecode.py", line XX, in <module>
from utils.myutils1 import myclass
ModuleNotFoundError: No module named 'utils'
问题是 Pycharm 为您做的事情很少,这就是它无法在终端中运行的原因。因此,在告诉您需要做什么之前,我将告诉您 PyCharm 本身所做的两件事。
Python控制台
当您从 Pycharm 启动 Python 控制台时,会使用首选项执行一些代码。
正如你所看到的,有两个选项
[X] Add content roots to PYTHONPATH
[ ] Add source roots to PYTHONPATH
然后还有一个启动脚本。所以它的作用是将项目的根添加到 python 的路径中。主要由两种方式控制sys.path
and PYTHONPATH
环境变量
如果我在 Python 控制台中运行以下代码
>>> import sys
>>> sys.path
['/Applications/PyCharm.app/Contents/helpers/pydev',
'/Applications/PyCharm.app/Contents/helpers/pydev',
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python27.zip',
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7', ....
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7/site-packages',
'/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27']
如你看到的'/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27'
已添加到 Python 终端。
Python 配置
当您使用 Pycharm 配置为在代码中运行时,您有类似的两个选项。
我们可以改变我们的代码somecode.py
到下面
import os
print (os.environ['PYTHONPATH'])
import sys
print (sys.path)
/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27
['/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27/folder1',
'/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27', ....,
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7/site-packages']
从输出中我们可以看到PYTHONPATH
设置为当前项目文件夹。
从终端运行
现在让我们运行somecode.py
从终端与我们所做的修改。
$ python somecode.py
Traceback (most recent call last):
File "somecode.py", line 2, in <module>
print (os.environ['PYTHONPATH'])
File "/Users/tarun.lalwani/.virtualenvs/folderstructure27/bin/../lib/python2.7/UserDict.py", line 40, in __getitem__
raise KeyError(key)
KeyError: 'PYTHONPATH'
所以这表明没有PYTHONPATH
当我们在终端运行它时。让我们通过删除来再次运行它print(os.environ['PYTHONPATH'])
代码。您将得到以下输出
['/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27/folder1', ...
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7/site-packages']
Traceback (most recent call last):
File "somecode.py", line 7, in <module>
from utils.myutils1 import myclass
ImportError: No module named utils.myutils1
如你看到的folder1
被添加到sys.path
因为它是包含的文件夹somecode.py
,但根文件夹尚未添加。终端中的修复很简单,就是在 PYTHONPATH 中设置根目录路径。
PYTHONPATH=`pwd`/.. python somcode.py
现在代码也可以在终端上运行。
但它们的工作方式与Python Console不同。
重要的提示:
在远程解释器上使用 PyCharm 的 Python 控制台。
If running the python console using the remote interpreter option pycharm will fail. This is because it will append the path of the local PC and not the path of the remote server.
In order to fix this problem one has to add a mapping between the local PC directory and the remote server path.