现在的位置: 首页 > 综合 > 正文

python import字符串

2013年05月31日 ⁄ 综合 ⁄ 共 653字 ⁄ 字号 评论关闭

通常我们导入我们需要的包,通过下列的方式:

import mypack

或者:

from test import mypack

但是我们可能根据不同的情况导入不同的包,例如根据操作系统来导入不同的配置文件,不同资源文件,你可以这样写:

if os is win:

     from local import winconfig

     from res import winres

elif os is linux:

    from local import linuxconfig

    from res import linuxres

elif os is mac:

    from local import macconfig

    from res import macres

else  raise Exception( 'not support' )

但是你觉得有点繁琐,你想直接得到当前系统的字符串值,然后通过直接导入字符串代表的包

那么上面的那么多行代码就可以用2行完成:

os = GetOs()

from local import os + 'config'

from res import os + 'res'

但是我告诉你,如果你这样写,python解释器会告诉你,语法错误。那么要怎么做呢?

可以使用importlib,这个包是2.7才加入的,如果你比较早的版本,那么就使用

__import__()

看下正确的代码:

import importlib

importlib.import_module( ‘local.’ + os + 'config' )

importlib.import_module( ‘local.’ + os + 'res' )

抱歉!评论已关闭.