Python中几种导入模块的方式

来源:互联网 发布:mac怎么看运行的程序 编辑:程序博客网 时间:2024/06/06 04:19

模块内部封装了很多实用的功能,有时在模块外部调用就需要将其导入。常见的方式有如下几种:

1 . import

>>> import sys>>> sys.path['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']

最常见的方式,直接将要导入的模块名称写在后面导入。

2 .from .. import ..
与import类似,只是更明确的要导入的方法或变量,比如:

>>> from sys import path>>> path['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']

但是会造成命名空间的污染,更推荐使用import。
3 . 用名称字符串导入模块
我们可能想这样导入模块:

>>> import "sys"SyntaxError: invalid syntax

python import接收的是变量而不是字符串,那将”sys”赋值给一个变量呢?

>>> x="sys">>> import xTraceback (most recent call last):  File "<pyshell#4>", line 1, in <module>    import xImportError: No module named 'x'

这样也不行,这样做的意思是导入名为x的模块而非x代表的sys模块。

我们需要用到exec函数:

>>> x="sys">>> exec("import "+ x)>>> sys.path['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']

将导入语句构建成字符串并传递给exec函数执行。

exec缺点是每次执行都要编译,运行多次会影响性能。

更好的方式是使用__import__ 函数。

>>> x="sys">>> sys = __import__(x)>>> sys.path['', 'C:\\Python34\\Lib\\idlelib', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']

这种方式需要一个变量保存模块对象,以便后续调用。

0 0