2017-07-26 47 views
0

我有2个python脚本。Python - 导入模块只有一次

satellite_utils.py 
apply_errata.py 

,我运行的脚本是:在satellite_utils.py定义

python3.4 apply_errata.py 

apply_errata.py通话功能。

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

如果我定义apply_errata.pylogging和参考在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 

什么办法可以避开everyfile import语句?

+0

为什么你不想在每个文件中导入它? – bereal

+4

如果你想使用一个模块,你需要导入它。导入模块并不意味着它被多次加载。这只是意味着你正在代码中引用它。 – MrE

+2

每个需要'logging'的模块都应该'导入​​日志记录'。 – user2357112

回答

-1

您可以通过在脚本中导入必要的库,然后使用wildchar将该脚本中的所有内容导入到另一个脚本中。通过这样做,您不会再导入它们,而是引用它们,并且可以在第二个脚本中使用它们,就像在friest脚本中使用它们一样。

例如: 1. Script1.py

import logging 
import something 
..... 
... 
log_i=logging.info 
log_d=logging.debug 
  • 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 
    
  • 这里日志记录时在进口SCRIPT1和我将所有从Script1导入到Script2,这意味着Script1中使用的所有库,变量和函数定义都可以从Script2访问和修改。因此,我在Script2中直接使用了日志记录,而没有任何声明/分配。

    根据@ anugrah的评论,您可以使用__init__.py初始化目录中的模块,以便可以像上述方法一样导入和使用它们。所以,如果你选择这种方法,然后它会像

    ABC/__ init__.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") 
    
    +0

    您也可以将它们添加到'__init __。py'文件中! 请参阅http://effbot.org/pyfaq/what-is-init-py-used-for.htm – anugrah

    +0

    您对'__init __。py'的描述是错误的,并且将所有导入填充到一个模块中,并且导入* “这对于循环导入问题来说是一条快捷之路。 – user2357112