arkenstone

之前遇到一个问题,在Pycharm或IPython之类的IDE上运行脚本正常,但是直接运行或cmd命令行运行的时候报了模块未能找到的错误——ImportError: No Module named ...。 这是啥情况?

Python在启动解释器(Interpreter)的时候不光会导入环境变量中sys.path发现的模块,还会导入当前工作目录下的模块。当你在IDE中启动解释器时,当前的工作目录就是项目目录,能顺利调用同项目中的模块;但是当你通过命令行启动时,当前工作目录为你启动解释器时所在的目录,如果当时的位置不是项目目录,那么项目目录中的模块就不会被找到,因此运行的时候报错:ImportError: No Module named ...

具体例子如下:

在上面的项目中有如下脚本,运行trainingset_selection.py需要调用另一个目录下的connect_db.py。如果在命令行中运行的时候会出现以下错误:

trainingset_selection.py的前8行如下:

__author__ = "Arkenstone"

import os
import sys
# get current working directory -- Better to set the PYTHONPATH env variable
# current_working_directory = "C:\Users\username\PycharmProjects\projectName"
# sys.path.append(current_working_directory)
from connectDB.connect_db import extractDataFromDB

解决方法:
方法很简单,就是把模块路径提供给解释器:

  1. (推荐) 把模块路径放到环境变量中作为全局变量(sys.path能扫描到)。
    添加PYTHONPATH = /path/to/your/module

  2. 显式的在运行的脚本中添加
    把上面代码中的第6, 7行的注释去掉就是了,效果同上。

import sys
sys.path.append(\'/path/to/your/module\')

做完这些后再运行就不会报错了。

参考:

  1. http://stackoverflow.com/questions/15514593/importerror-no-module-named-when-trying-to-run-python-script
  2. http://stackoverflow.com/questions/8321130/python-module-import-issues-in-command-prompt

分类:

技术点:

相关文章:

  • 2021-04-30
  • 2021-08-26
  • 2021-10-18
  • 2021-08-13
  • 2021-12-09
  • 2021-06-17
  • 2021-10-08
猜你喜欢
  • 2021-05-17
  • 2021-06-17
  • 2021-04-10
  • 2021-05-01
  • 2021-08-01
  • 2021-07-19
相关资源
相似解决方案