Python模块导入问题

时间:2018-07-18 17:41:06

标签: python-2.7 import module

为什么在与模块相同的文件夹中完成模块导入工作正常,但是从父路径导入却不行?

工程

从'/ django / website / tools / utils'调用时

 utils]$ python2.7 -c 'import Tools;print Tools.Tools().process("msvc_util1",{})'
 {
    "hash": "caf59fd97f90556076f1f10b53ba50242f1b7443",
.......
....



不起作用

从'/ django / website / tools /'调用时

tools]$ python2.7 -c 'from utils import *;print Tools.Tools().process("msvc_util1",{})'
Unexpected error: (<type 'exceptions.ImportError'>, ImportError('No module named msvc_util1',), <traceback object at 0x7f745653bb90>)
Traceback (most recent call last):
  File "utils/Tools.py", line 18, in process
    module = __import__(tool)
ImportError: No module named msvc_util1



其他详细信息

  1. 实用程序路径列表


utils]$ ls
__init__.py   msvc_util1.py   msvc_util.py   test1.py  test.pyc  Tools.pyc
__init__.pyc  msvc_util1.pyc  msvc_util.pyc  test.py   Tools.py
  1. Tools.py


utils]$ cat Tools.py
from __future__ import print_function
import sys
import traceback
#from tools.utils import msvc_util1
#from utils import *

class Tools(object):
    def __new__(cls):
        if not hasattr(cls, 'instance') or not cls.instance:
            cls.instance = super(Tools, cls).__new__(cls)#object.__new__(cls)
        return cls.instance

    def process(self,tool,params):
        res = None
        try:
           if (  tool not in self.__dict__ ) :
               module = __import__(tool)
               class_ = getattr(module, tool)
               instance = class_()
               self.__dict__[tool] = instance
           res = self.__dict__[tool].process(params)
        except:
           #print("Unexpected error:%s" % str(traceback.print_exc()),file=sys.stderr)
           print("Unexpected error: " + str(sys.exc_info()),file=sys.stderr)
           print(traceback.print_exc(),file=sys.stderr)
           pass

        return res
  1. __ init __。py


  utils]$ cat __init__.py
    __all__ = ["msvc_util","Tools"]

0 个答案:

没有答案