【发布时间】:2020-10-03 00:05:22
【问题描述】:
每当我在 PyCharm 中输入 import pygame 时,它都会说模块没有安装,但我可以在终端中以 python 模式导入它。
【问题讨论】:
-
在您的脚本中。您可以检查
lib或module是否出现在sys.path列表中。可能不是。你需要附加它。打印sys.path列表并检查。 -
@Adam 我该怎么做?
每当我在 PyCharm 中输入 import pygame 时,它都会说模块没有安装,但我可以在终端中以 python 模式导入它。
【问题讨论】:
lib 或 module 是否出现在 sys.path 列表中。可能不是。你需要附加它。打印sys.path 列表并检查。
在你的 py 脚本中:
import sys
##lets check if this module appears in the sys.path
exist = False
for path in sys.path:
if 'pygame' in path:
print path
exist = True
if not exist:
sys.path.append('... the path to the pygame dir.. where the __init__.py')
我建议将pygame 的路径添加到要从中执行脚本的shell 的PYTHONPATH 环境变量中。而不是直接在py脚本中编辑sys.path。
PYTHONPATH 是一个环境变量,您可以设置它以添加其他目录,python 将在其中查找模块和包。例如:
如果您在windows,您可以使用set 命令扩展PYTHONPATH。
在 Linux 中:
# make python look in the pygameDirPath subdirectory of your home directory for
# modules and packages
export PYTHONPATH=${PYTHONPATH}:${HOME}/pygameDirPath
【讨论】: