Python - 仅导入模块一次

时间:2017-07-26 17:12:36

标签: python

我有2个python脚本。

satellite_utils.py
apply_errata.py

我运行的脚本是:

python3.4 apply_errata.py

apply_errata.py调用satellite_utils.py中定义的函数。

现在我使用模块logging来记录我的消息。我想只导入一次而不必在每个脚本中声明它。

如果我在logging中定义apply_errata.py并在satellite_utils.py中对其进行了引用,我会得到:

Traceback (most recent call last):
  File "apply_errata.py", line 20, in <module>
    satellite_utils.applyErrata(args.release, args.all, args.rollback)
  File "/root/config-3.1.21/automated-os-patching/satellite_utils.py", line 34, in applyErrata
    applyErrataOnSystem(system, release, automaticRollback, [erratum])
  File "/root/config-3.1.21/automated-os-patching/satellite_utils.py", line 39, in applyErrataOnSystem
    logging.warning('is when this event was logged.')
NameError: name 'logging' is not defined

任何方式我都可以避免每个文件中的import语句?

2 个答案:

答案 0 :(得分:0)

您可以像这样使用 satellite_utils 中的日志记录实例:

# in apply_errata.py
import satellite_utils
satellite_utils.logger.info('hello there')

# in apply_errata.py
from satellite_utils import logger
logger.info('hi there')

这是可行的,因为在 Python 文件中定义的任何名称都附加到该文件的全局范围(在 Python 文件中是模块,因此文件 == 模块),并且任何人都可以访问。

重要的是要指出,这不是规范和首选的做事方式。你是成年人了,你可以自己决定。

为什么多次导入模块还不错:它们被 Python 缓存在 sys.modules dict 中,所以下次导入时,您只会获得该缓存副本。 Python docs on sys.modules

答案 1 :(得分:-1)

您可以通过在脚本中导入必要的库,然后使用wildchar将该脚本中的所有内容导入另一个脚本来实现。通过执行此操作,您不会再次导入所有这些,而是​​引用它们,并且可以在第二个脚本中使用它们,就像您在friest脚本中使用它们一样。

例如: 1. Script1.py

import logging
import something
.....
...
log_i=logging.info
log_d=logging.debug
  1. Script2.py

    from Script1 import * #import all in Script1
    log_i("this is info log")
    log_d("this is debug log")#use the imported data
    
  2. 此处日志记录在Script1中导入,我将所有从Script1导入到Script2,这意味着Script1中使用的所有库,变量,函数定义都可以从Script2访问和修改。因此,我在Script2中没有任何声明/赋值就直接使用日志记录。

    根据@ anugrah的评论,您可以使用__init__.py初始化目录中的模块,以便像上述方法一样导入和使用它们。因此,如果您选择此方法,那么它就像

    <强> ABC / __初始化__。PY

    <强> ABC / modules.py

    import logging,os,sys
    log_i=logging.info
    log_d=logging.debug
    

    <强> Script1.py

    from abc.modules import log_* #now I'm importing only log_i,log_d
    log_i("this is info log")
    log_d("this is debug log")
    
相关问题