【发布时间】:2019-01-04 16:44:56
【问题描述】:
我有一个 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 机器上运行时,有一个类似的 question 关于导入问题。但是,我的问题与在 Mac 上使用 iPython vs python 运行脚本有关。
【问题讨论】:
-
@Dyno 我编辑了我的问题以解释与可能重复问题的区别。
-
@wigging 我下面的解决方案对你有用吗?如果没有,你能说为什么不吗?
-
@wigging 谢谢,我完全错过了这一区别,目前的答案似乎都在使用相同的思路。希望您的修改将有助于找到解决方案。
标签: python python-3.x ipython