我有一个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与python
来运行脚本有关。
发布于 2018-07-27 22:36:31
在from params import serial
insert上方:
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]) )
发布于 2018-07-27 22:30:58
如果要引用基本proj
目录的导入,则必须将PYTHONPATH
设置为该目录。目前,honda.py
正在寻找一种名为params
的moudule
,它在自己的module
中。
~$ cd path/to/project
~$ PYTHONPATH=$(pwd)
或者,您可以使用relative imports
。
发布于 2018-07-27 22:33:58
位置的问题,你应该写下params.py的完整路径。Ipython有一个字符,可以用linux命令.so先打开你的cd目录,解释器就可以找到这个params.py了。但是python命令需要params.py的完整路径。这就是您不能运行处理的原因。
https://stackoverflow.com/questions/51559978
复制相似问题