gpt4 book ai didi

Python在父目录中找不到模块

转载 作者:行者123 更新时间:2023-12-01 01:44:21 24 4
gpt4 key购买 nike

我的 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 命令的方法不起作用?

注意 - 上面的示例是使用 Anaconda Python 发行版在 Mac 上执行的。还有类似的question关于在 Windows 与 Linux 计算机上运行时的导入问题。但是,我的问题与在 Mac 上使用 iPython 与 python 运行脚本有关。

最佳答案

上面的from params import serial插入:

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

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

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

如果您希望在从 project 的父目录运行脚本时能够将 params 导入到 cars/honda.py 中,您可以使用以下内容:

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

关于Python在父目录中找不到模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51559978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com