1. 程式人生 > >Python內建函式__import__和eval用法

Python內建函式__import__和eval用法

由模組的名稱(字串)動態地去呼叫函式

import glob,os

modules = []
for module_file in glob.glob("*-plugin.py"):
    try:
       module_name,ext = os.path.splitext(os.path.basename(module_file))
       module = __import__(module_name)
       modules.append(module)
    except ImportError:
       pass #ignore broken modules
    for module in modules:
       module.hello()
由模組獲取函式:
def getfunctionbyname(module_name,function_name):
    module = __import__(module_name)
    return getattr(module,function_name)
<span style="font-family: Arial, Helvetica, sans-serif;">import copy</span>
<span style="font-family: Arial, Helvetica, sans-serif;">import os</span>
import sys
from importlib import import_module

def import_string(dotted_path):
    """
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImportError if the import failed.
    """
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        msg = "%s doesn't look like a module path" % dotted_path

    module = import_module(module_path)

    try:
        return getattr(module, class_name)
    except AttributeError:
        msg = 'Module "%s" does not define a "%s" attribute/class' % (
            dotted_path, class_name)

函式實現延遲化的模組匯入 :

class LazyImport:
      def __init__(self,module_name):
          self.module_name = module_name
          self.module = None
      def __getattr__(self,name):
          if self.module is None:
             self.module = __import__(self.module_name)
          return getattr(self.module,name)
string = LazyImport("string")
print string.lowercase

eval()把list,tuple,dict和string相互轉化:

ast.literal_eval