python - Python在父目录中找不到模块
问题描述
我有一个 Python 项目的文件夹结构,如下所示:
proj/
├── cars
│ ├── honda.py
│ └── volvo.py
├── trucks
│ ├── chevy.py
│ └── ford.py
├── main.py
└── params.py
内容params.py
:
""" Parameters used by other files. """
serial = '12-411-7843'
内容honda.py
:
""" Information about Honda car. """
from params import serial
year = 1988
s = serial
print('year is', year)
print('serial is', s)
从proj/
文件夹中,我可以使用 iPython 运行脚本:
$ cd path/to/proj/
$ ipython
In [1]: run cars/honda.py
year is 1988
serial is 12-411-7843
如果我尝试使用该python
命令运行脚本,我会收到一个未找到模块的错误params.py
:
$ cd path/to/proj/
$ python cars/honda.py
Traceback (most recent call last):
File "cars/honda.py", line 5, in <module>
from params import serial
ModuleNotFoundError: No module named 'params'
为什么使用python
命令的方法不起作用?
注意 - 上面的示例是在 Mac 上使用 Anaconda Python 发行版执行的。在 Windows 和 Linux 机器上运行时,有一个关于导入问题的类似问题。但是,我的问题与python
在 Mac 上使用 iPython vs 运行脚本有关。
解决方案
上面from params import serial
插入:
import sys
[sys.path.append(i) for i in ['.', '..']]
这会将您当前的工作目录及其父目录添加到您可以从中导入的位置列表中。
从父目录运行脚本时处理导入proj
如果您希望在从 的父目录运行脚本时能够导入params
,您可以使用以下命令:cars/honda.py
project
import sys
import os
from functools import reduce
# allow imports when running script from within project dir
[sys.path.append(i) for i in ['.', '..']]
# allow imports when running script from project dir parent dirs
l = []
script_path = os.path.split(sys.argv[0])
for i in range(len(script_path)):
sys.path.append( reduce(os.path.join, script_path[:i+1]) )