[英]ImportError when running python script
I have a nested python script that imports a module from another directory. 我有一个嵌套的python脚本,可从另一个目录导入模块。 When I run the nested python script as: 当我以如下方式运行嵌套的python脚本时:
python dir_a/dir_b/script.py
It throws an Import Error that it is unable to load the specified module. 它将引发无法导入指定模块的导入错误。 However when I run the script as: 但是,当我运行脚本为:
python -m dir_a.dir_b.script
It runs successfully. 它运行成功。 Any idea why is that? 知道为什么吗?
-m
switch adds the current directory to sys.path
, which contains the modules that script.py
imports, while without the -m
switch dir_a/dir_b
is added to sys.path
instead. -m
开关将当前目录添加到sys.path
,其中包含script.py
导入的模块,而没有-m
开关, dir_a/dir_b
添加到sys.path
。 See python's command-line documentation . 请参阅python的命令行文档 。
You can also try following, 您也可以尝试关注,
sys.path.insert("relative path of import_module from script.py")
import "import_module"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.