程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Dynamic loading of Python modules

編輯:Python

Python Dynamic loading of modules

List of articles

      • Python Dynamic loading of modules
        • 1.`__import__`
        • 2.`fromlist`
        • 3.`importlib.import_module`

1.__import__

Such scenes are often seen in projects , According to environment variable , Load different configurations .

Test environment :config_dev.py

db_host = '127.0.0.1'

Formal environment :config_pro.py

db_host = '192.168.0.1'

This is the case __import__ To dynamically load , Simple examples such as :

project_env = 'dev'
if project_env == 'dev':
config = __import__("config_dev")
else:
config = __import__("config_pro")
print(config.db_host)
# result :
# 127.0.0.1

2.fromlist

__import__ There are a lot of parameters , among name Is a must , Among other parameters fromlist Is an important parameter . In the previous example , The two configuration and import module files are in the same folder , That's not there ? Now? , Change project results :

├── conf
│ ├── __init__.py
│ ├── config_dev.py
│ └── config_pro.py
└── demo.py

Change it demo.py Code for :

project_env = 'dev'
if project_env == 'dev':
config = __import__("conf.config_dev")
else:
config = __import__("conf.config_pro")
print(config)

Output results :

<module 'conf' from 'D:\\project\\python\\black_api\\demo\\conf\\__init__.py'>

See that ? Our intention is to import different modules ,config_dev or config_pro, But the actual import is conf modular , Not in line with our expectations . In this case , Need to use fromlist Parameters :

project_env = 'pro'
if project_env == 'dev':
config = __import__("conf.config_dev", fromlist="config_dev")
else:
config = __import__("conf.config_pro", fromlist="config_pro")
print(config)

Output results :

<module 'conf.config_pro' from 'D:\\project\\python\\black_api\\demo\\conf\\config_pro.py'>

Conclusion : In the use of __import__ Function time ,name If the address of contains the name of the package , Be sure to use fromlist Parameter to indicate which module in the package to import , Otherwise, the entire package will be imported .

3.importlib.import_module

importlib Modular import_module Method compared to __import__ More friendly , More convenient to use . Let's take an example 2 Project structure , modify demo.py Code for :

import importlib
project_env = 'dev'
if project_env == 'dev':
# Absolutely import 
config = importlib.import_module('conf.config_dev')
else:
# Relative Import 
config = importlib.import_module('.config_pro', package='conf')
print(config.db_host)

When using relative Import , Be sure to name Add a dot in front


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved