1
fy 2016-03-14 02:03:16 +08:00
楼主你问之前不妨先试一下:
if True: import re else: import json In [51]: re Out[51]: <module 're' from 'd:\\python34\\lib\\re.py'> In [52]: json --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-52-832ed6b85533> in <module>() ----> 1 json NameError: name 'json' is not defined |
2
ericls 2016-03-14 02:17:21 +08:00
if a:
import A if b: import B if c: import C |
3
gx 2016-03-14 03:15:07 +08:00
看一下 import_module 实现,当然, 3.x 直接用了。
"""Backport of importlib.import_module from 3.x.""" # While not critical (and in no way guaranteed!), it would be nice to keep this # code compatible with Python 2.3. import sys def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in xrange(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: raise ValueError("attempted relative import beyond top-level " "package") return "%s.%s" % (package[:dot], name) def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ if name.startswith('.'): if not package: raise TypeError("relative imports require the 'package' argument") level = 0 for character in name: if character != '.': break level += 1 name = _resolve_name(name[level:], package, level) __import__(name) return sys.modules[name] |
4
gx 2016-03-14 03:18:20 +08:00
2.x 的朋友移步 /PATH_TO_YOUR_PYTHON_LIB_FOLDER/importlib/__init__.py
|
5
restran 2016-03-14 08:46:47 +08:00
还可以根据字符串动态导入包
```py 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 raise ImportError(msg) module = import_module(module_path) try: return getattr(module, class_name) except AttributeError: msg = 'Module "%s" does not define a "%s" attribute/class' % ( module_path, class_name) raise ImportError(msg) ``` 使用方法 `import_string('a.b.c')` |
6
knightdf 2016-03-14 08:52:29 +08:00
if else.....
import 几乎可以写在任何位置。。。写函数里也行,用的时候再 import |
7
jimzhong 2016-03-14 08:54:13 +08:00
import 本来就是动态的哦
|
8
Anthony117 2016-03-14 08:57:30 +08:00
3.1+ 的话 importlib
https://docs.python.org/3/library/importlib.html |
9
mengzhuo 2016-03-14 09:16:26 +08:00 via iPhone
标题党… ifelse 这叫动态 import ?
我还以为说的是生成动态 class 和模块呢…… 我实现过这个,很好玩,感兴趣的同学可以联系我 |
10
ksc010 2016-03-14 09:23:22 +08:00
应该是根据变量来导入不同的模块
原来也遇到这样的问题,需要实现一个插件机制 解决的办法有点笨: 现在一个目录(plugs/)的__init__.py 导入所有的需要的插件模块 然后 在里面定义一个 函数 下面是简化代码 def getPlug(plugname): glb=globals() return glb[plugname] 其它地方要引用的话 直接 from plugs import getPlug plug=getPlug('plugA') |
13
nevin47 2016-03-14 10:41:02 +08:00
|
14
leyle 2016-03-14 11:29:33 +08:00
from importlib import import_module
|
15
dsp2138 OP |
17
Phant0m 2016-03-14 11:47:47 +08:00
|
18
mengzhuo 2016-03-14 12:07:39 +08:00
|
21
ToughGuy 2016-03-14 16:04:28 +08:00
module = importlib.import_module('os.path')
|
24
mengzhuo 2016-03-15 10:10:43 +08:00 via iPhone
|
25
gx 2016-03-15 16:28:22 +08:00
|