从终端运行脚本时出现 ModuleNotFoundError [英] ModuleNotFoundError when running script from Terminal
问题描述
我有以下文件夹结构:
应用
__init__.py
utils
__init__.py
transform.py
__init__.py
fish.py
在fish.py中,我按如下方式导入
transform
:import utils.transform
.In fish.py I'm importing
transform
as following:import utils.transform
.当我从 Pycharm 运行 fish.py 时,它运行得非常好.但是,当我从终端运行 fish.py 时,出现错误
ModuleNotFoundError: No module named 'utils'
.When I'm running fish.py from Pycharm, it works perfectly fine. However when I am running fish.py from the Terminal, I am getting error
ModuleNotFoundError: No module named 'utils'
.我在终端中使用的命令:来自应用程序文件夹
python products/fish.py
.Command I use in Terminal: from app folder
python products/fish.py
.我已经研究了此处建议的解决方案:从不同文件夹导入文件,将应用程序文件夹的路径添加到
sys.path
帮助中.但是我想知道是否还有其他方法可以在不向fish.py
中添加两行代码的情况下使其工作.因为我/products目录下有很多脚本,不想每条都加两行代码.I've already looked into the solutions suggested here: Importing files from different folder, adding a path to the application folder into the
sys.path
helps. However I am wondering if there is any other way of making it work without adding two lines of code into thefish.py
. It's because I have many scripts in the /products directory, and do not want to add 2 lines of code into each of them.我查看了一些开源项目,并且看到了许多从并行文件夹导入模块而不向 sys.path 添加任何内容的示例,例如这里:https://github.com/jakubroztocil/httpie/blob/master/httpie/plugins/builtin.py#L5
I looked into some open source projects, and I saw many examples of importing modules from a parallel folder without adding anything into sys.path, e.g. here: https://github.com/jakubroztocil/httpie/blob/master/httpie/plugins/builtin.py#L5
如何让它以同样的方式适用于我的项目?
How to make it work for my project in the same way?
推荐答案
您可能想要运行
python -m products.fish
.它和python products/fish.py
的区别在于前者大致相当于在 shell 中做import products.fish
(但带有__name__
code> 设置为__main__
),而后者不知道它在包层次结构中的位置.You probably want to run
python -m products.fish
. The difference between that andpython products/fish.py
is that the former is roughly equivalent to doingimport products.fish
in the shell (but with__name__
set to__main__
), while the latter does not have awareness of its place in a package hierarchy.这篇关于从终端运行脚本时出现 ModuleNotFoundError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!