我知道这个问题已经被问过几十次了,但我看不出我做错了什么。我正在尝试从不同的目录导入 python 2.7 中的模块。我将不胜感激一些意见,以帮助我理解为什么这种方法不起作用。我的 raspbian 系统上有以下目录结构:
/home/pi/
...projects/__init__.py
...projects/humid_temp.py
...python_utilities/__init.py__
...python_utilities/tools.py
我正在调用 humid_temp.py,我需要在 tools.py 中导入一个函数。它们的内容如下所示:
湿度温度.py:
import os
import sys
sys.path.append('home/pi/python_utilities')
print sys.path
from python_utilities.tools import *
工具.py:
def tail(file):
#function contents
return stuff
print sys.path
输出包含/home/pi/python_utilities
我没有弄乱我的 __init__.py
是吗?
我还排除了该路径可能存在的权限问题,因为我给了它完整的 777 访问权限,但我仍然点击了
ImportError: No module named python_utilities.tools.
我错过了什么?
最佳答案
当你想导入类似的东西时 -
from python_utilities.tools import *
您需要将 python_utilities
的父目录添加到 sys.path
,而不是 python_utilities
本身。所以,你应该添加类似 -
sys.path.append('/home/pi') #Assuming the missing of `/` at start was not a copy/paste mistake
另外,请注意,from <module> import *
是错误的,您应该考虑只导入所需的项目,您可以查看问题 - Why is "import *" bad? - 了解更多详情。
关于Raspberry Pi 上的 Python 导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32346837/