简体   繁体   English

运行python脚本时出现ImportError

[英]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.

相关问题 在Jenkins中运行Python脚本时的ImportError - ImportError when running Python script in Jenkins 运行已安装的脚本时出现Python ImportError - Python ImportError when running an installed script ImportError:在Raspberry Pi上运行python脚本时,没有名为“ azure”的模块 - ImportError: No module named 'azure' when running python script on Raspberry Pi 在crontab中运行python脚本时出现“ ImportError:没有名为praw的模块”错误 - “ImportError: No module named praw” error when running python script in crontab 在JMeter中运行Python脚本时出现模块ImportError - Module ImportError in running Python Script in JMeter 将Python脚本作为plist运行会导致ImportError - Running python script as plist results in ImportError 使用cmd文件运行python脚本会导致ImportError - Running python script with cmd file results in ImportError 运行med2image脚本时出现ImportError - ImportError when running med2image script 在bash脚本中运行时刮擦“ ImportError” - Scrapy “ImportError” when running inside bash script python 脚本 ImportError:在 Automator 中运行 shell 脚本时没有名为“webbot”的模块 - python script ImportError: No module named 'webbot' when running shell script in Automator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM