- Работа с модулями в Python
- [править] Вопросы и ответы
- [править] Как посмотреть список загруженных модулей?
- [править] Как загрузить модуль динамически?
- [править] Как посмотреть список доступных модулей?
- [править] Как обновить существующие пакеты?
- [править] Как использовать virtualenv?
- [править] Как сделать virtualenv перемещаемым?
- [править] Когда выполняешь тестирование, можно ли подменять функции или классы и подсовывать нужные результаты?
- [править] Как посмотреть список доступных модулей?
- [править] Как посмотреть, какая версия пакета доступна для импорта?
- [править] Как поднять локальный репозиторий eggs?
- [править] Как перезагрузить уже загруженный модуль, если он был изменен в ходе работы программы?
- Reload or Unimport Module in Python
- Unimport a Module in Python
- Reload a Module in Python
- Related Article — Python Module
- Python Language Importing modules Re-importing a module
- Python 2
- Python 3
Работа с модулями в Python
Про Python часто говорят, что это язык, который идёт с батарейками в комплекте. Это означает, что кроме собственно языка, вы получаете ещё множество библиотек, использующихся во всех случаях жизни.
Прежде всего для работы в таких областях:
- Файловая система
- Процессы
- Дата и время
- Случайные числа
- Регулярные выражения
- TCP/IP
- XML
- JSON
Импорт любого модуля выполняется командой import (она имеет несколько форм):
Кроме собственно встроенной библиотеки языка, доступны ещё десятки тысяч пакетов к инсталляции из внешнего репозитория PyPI (38350 на конец 2013 года).
Первая десятка наиболее популярных модулей (по количеству загрузок):
1st distribute 35,957,324 2nd virtualenv 31,956,769 3rd setuptools 29,579,733 4th certifi 28,271,429 5th requests 28,090,908 6th boto 27,397,110 7th wincertstore 25,402,949 8th pip 23,449,879 9th six 21,289,715 10th pbr 20,756,750
Инсталляция внешнего модуля выполняется одной командой:
Лучше использовать так называемую виртуальную среду virtualenv, в этом случае пакет инсталлируется не глобально в систему, а в локальном каталоге, собственно в виртуальной среде, в которой вы работаете.
[править] Вопросы и ответы
[править] Как посмотреть список загруженных модулей?
import types def imports(): for name, val in globals().items(): if isinstance(val, types.ModuleType): yield val.__name__
- How to list imported modules?
[править] Как загрузить модуль динамически?
[править] Как посмотреть список доступных модулей?
from pkgutil import iter_modules for module in iter_modules(): .
[править] Как обновить существующие пакеты?
$ pip install pip-review $ pip-review --local --interactive
[править] Как использовать virtualenv?
При использовании virtualenv локально из исходников:
$ curl -O https://pypi.python.org/packages/source/v/virtualenv/virtualenv-X.X.tar.gz $ tar xvfz virtualenv-X.X.tar.gz $ cd virtualenv-X.X $ python virtualenv.py myVE
[править] Как сделать virtualenv перемещаемым?
Использовать ключ --relocatable. Окружение становится перемещаемым. Минус. что нужно вызывать virtualenv после каждой инсталляции нового модуля.
- Renaming a virtualenv folder without breaking it
[править] Когда выполняешь тестирование, можно ли подменять функции или классы и подсовывать нужные результаты?
Да, можно. Есть несколько модулей для этого, например mocker.
[править] Как посмотреть список доступных модулей?
[править] Как посмотреть, какая версия пакета доступна для импорта?
>>> import pkg_resources >>> pkg_resources.get_distribution("blogofile").version '0.7.1'
[править] Как поднять локальный репозиторий eggs?
Для этого лучше всего использовать collective.eggproxy (англ.) . После того как он поднимется, можно указывать локальный репозиторий например в pip и в easy_install.
easy_install -i http://localhost:8888/ -H "*localhost*" iw.fss
env/bin/pip install -v --index-url http://127.0.0.1:48888/ six
Или в конфигурационных файлах:
[global] index-url = http://localhost:8888/
[easy_install] index_url = http://localhost:8888/
[buildout] index = http://localhost:8888/
[править] Как перезагрузить уже загруженный модуль, если он был изменен в ходе работы программы?
import module1 #. # Later on: module1 = reload( module1 )
Информация о Python на xgu.ru | ||
---|---|---|
Реализации | Cython • Psyco • PyPy | |
Веб-фреймворки | Django • Flask • Zope | |
IDE | Pydev • NetBeans | |
Курсы | Python для сетевых инженеров | |
Другое | aalib • ctypes • gevent • mpmath • pjsua • Pandas • pyparsing • virtualenv • GMPY • IPython • Jinja2 • Python и Vim • Работа с модулями в Python • SWIG • Scapy • SciPy • Работа с датой и временем в Python • Python как shell • Web и Python • Алгоритмы, сложные структуры данных и дискретная математика в Python • Анализ кода Python • Интеграция Python с другими языками • Объекты и классы в Python • Оформление кода Python • Параллелизм и конкурентное исполнение в Python • Профайлинг в Python • Работа с базами данных в Python • Работа с операционной системой в Python • Работа с сетью в Python • Работа с текстами в Python • Работа с файлами в Python • Сравнение Python с другими языками • Тестирование в Python • Типы в Python • Элементы функционального программирования в Python • Элементы языка Python |
Reload or Unimport Module in Python
- Unimport a Module in Python
- Reload a Module in Python
Modules allow us to store definitions of different functions and classes in a Python file, and then such files can be used in other files. The pandas , NumPy , scipy , Matplotlib are some of the most widely used modules in Python.
We can also create our own modules in Python, which can increase modularity and simplify large programs.
Unimport a Module in Python
We use the import command to load a specific module to memory in Python. We cannot unimport a module since Python stores it in the cache memory, but we can use a few commands and try to dereference these modules so that we are unable to access it during the program. These methods, however, might fail at times, so please be careful.
The first is the del command. It is used to remove a variety of objects in Python. Removing the access of a module using this command is shown below.
import module_name del module_name
The sys.modules is a dictionary that can be viewed using the sys module and is used to store the references of a function and modules. We can remove the required module from this dictionary using the del command to remove its every reference. It is difficult to remove modules that have been referenced a lot, so one needs to be careful while using this. This method might produce unwanted results, so please be cautious.
if 'myModule' in sys.modules: del sys.modules["myModule"]
Reload a Module in Python
In case we have made changes to a module and wish to implement those changes without restarting the program, we can use the reload() function that will reload the required module.
The reload() function has a long history in Python. Till Python 2.7 it was a built-in function.
In Python 3.0 to Python 3.3, it was present in the imp library that was later deprecated and changed to importlib module, which contains functions for implementing the mechanisms of importing codes in files Python.
The following code shows how to use the reload() function.
import importlib reload(module_name)
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
Related Article — Python Module
Python Language Importing modules Re-importing a module
When using the interactive interpreter, you might want to reload a module. This can be useful if you’re editing a module and want to import the newest version, or if you’ve monkey-patched an element of an existing module and want to revert your changes.
Note that you can’t just import the module again to revert:
import math math.pi = 3 print(math.pi) # 3 import math print(math.pi) # 3
This is because the interpreter registers every module you import. And when you try to reimport a module, the interpreter sees it in the register and does nothing. So the hard way to reimport is to use import after removing the corresponding item from the register:
print(math.pi) # 3 import sys if 'math' in sys.modules: # Is the ``math`` module in the register? del sys.modules['math'] # If so, remove it. import math print(math.pi) # 3.141592653589793
But there is more a straightforward and simple way.
Python 2
import math math.pi = 3 print(math.pi) # 3 reload(math) print(math.pi) # 3.141592653589793
Python 3
The reload function has moved to importlib :
import math math.pi = 3 print(math.pi) # 3 from importlib import reload reload(math) print(math.pi) # 3.141592653589793
PDF — Download Python Language for free