Chinaunix首页 | 论坛 | 博客
  • 博客访问: 471227
  • 博文数量: 135
  • 博客积分: 1860
  • 博客等级: 上尉
  • 技术积分: 1441
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-05 20:39
文章分类
文章存档

2012年(2)

2011年(130)

2009年(2)

2008年(1)

我的朋友

分类: Python/Ruby

2011-08-11 16:46:17

python中的exec内置函数可以将一个字符串转换为python的一个可执行对象并且执行,如:
a = 'sys'
exec('import %s' %a)
dir(sys)
 
结果如下:
>>> dir(sys)
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'sys' is not defined
>>>
>>> a='sys'
>>>
>>> import a
Traceback (most recent call last):
  File "", line 1, in
ImportError: No module named a
>>>
>>> exec('import %s' %a)
>>> dir(sys)
['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
>>>
阅读(1277) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~