首页 > 解决方案 > 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 运行脚本有关。

标签: pythonpython-3.xipython

解决方案


上面from params import serial插入:

import sys
[sys.path.append(i) for i in ['.', '..']]

这会将您当前的工作目录及其父目录添加到您可以从中导入的位置列表中。

从父目录运行脚本时处理导入proj

如果您希望在从 的父目录运行脚本时能够导入params,您可以使用以下命令:cars/honda.pyproject

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]) )

推荐阅读