美文网首页
Python3 - import导入模块,编辑的过程中动态加载模

Python3 - import导入模块,编辑的过程中动态加载模

作者: fanglaoda | 来源:发表于2018-01-01 21:01 被阅读0次

import导入模块

cli的目录结构如下

➜  cli tree
.
├── __pycache__
│   └── test.cpython-36.pyc
├── demo1
├── demo2
│   ├── __pycache__
│   │   └── test2.cpython-36.pyc
│   └── test2.py
└── test.py

若直接在test.py中import test2则会报以下错误

➜  cli python3
Python 3.6.0 (default, Jan 23 2017, 14:53:49)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'test2'

通过以下方式查看import的搜索路径

>>> import sys
>>> sys.path
[
'', 
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', 
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3
]

所以可以将test2.Py的路径加入上面的目录的方式来解决

>>> sys.path
[
'', 
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', 
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
'/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3,
'./demo2/'
]
// 重新导入后没有再报错
>>> import test2
>>> 
>>> 

由于此时的test2.py文件内容为空

另开一个窗口编辑test2.py ,增加一个hello方法

15148114276369.jpg

回到左侧调用hello方法会报以下错误

>>> import test2
>>> test2.hello()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'test2' has no attribute 'hello'

当然可以通过推出在重新导入的方式是可以的,另一种方式就是该篇的第二个话题:动态加载

动态加载模块

场景:开了2个窗口同时编辑同一个文件,但又不想退出重进

>>> from imp import *
>>> reload(test2)
<module 'test2' from './demo2/test2.py'>

此时在调用hello方法即可

>>> test2.hello()
hello

相关文章

  • Python3 - import导入模块,编辑的过程中动态加载模

    import导入模块 cli的目录结构如下 若直接在test.py中import test2则会报以下错误 通过以...

  • python学习之-- 动态导入模块

    动态导入模块方法1: import 说明:1. 函数功能用于动态的导入模块,主要用于反射或者延迟加载模块。2. i...

  • 飞机大战

    飞机大战 导入模块的三种方式 import pygamefrom 模块名 import *(代表所有)from 模...

  • 飞机大战

    飞机大战 导入模块的三种方式 import pygamefrom 模块名 import *(代表所有)from 模...

  • python------飞机大战

    飞机大战 导入模块的三种方式 import pygamefrom 模块名 import *(代表所有)from 模...

  • 2018-11-06 插件化编程艺术

    动态导入运行时,根据用户需求(提供字符串),找到模块的资源动态加载起来。 内建函数__import__()__im...

  • 模块和包的创建与导入

    一、模块 在python中,模块就是python文件,其后缀为.py。我们通过import语句来导入模块或者导入模...

  • 2019-03-28/ES6新增特性-2

    一、import 导入整个模块的内容 导入单个或多个 动态import 二、export 命名导出 如果我们要导出...

  • python模块以及包管理

    一、模块的导入方式 1、 import方式导入(绝对导入):在后续代码中调用此模块中的类,函数,属性等都是通过:模...

  • 重点知识复习(异常处理)

    1.模块 导入模块(自定义模块,第三方模块,系统其他模块)import 模块 ----> 模块.内容from 模...

网友评论

      本文标题:Python3 - import导入模块,编辑的过程中动态加载模

      本文链接:https://www.haomeiwen.com/subject/tzcxnxtx.html