【问题标题】:How to import part of a module in python?如何在python中导入模块的一部分?
【发布时间】:2011-05-16 02:16:15
【问题描述】:

我需要使用 python 模块(在某些库中可用)。该模块如下所示:

class A:
  def f1():
  ...

print "Done"
...

我只需要 A 类的功能。但是,当我导入模块时,底部的代码(打印和其他)会被执行。有没有办法避免这种情况?本质上我需要导入模块的一部分:“from module1 import A”应该只导入A。有可能吗?

【问题讨论】:

    标签: python module import


    【解决方案1】:

    是的,当然:

    from module1 import A
    

    是通用语法。例如:

    from datetime import timedelta
    

    应该保护底部的代码在导入时不运行,如下所示:

    if __name__ == "__main__":
      # Put code that should only run when the module
      # is used as a stand-alone program, here.
      # It will not run when the module is imported.
    

    【讨论】:

    • 问题是它的现有模块和底部的代码没有像你提到的那样受到保护。
    • 这当然是在后台导入整个模块,但只是将其中的一部分放在命名空间中。例如。如果module1.A 仅依赖于module1.B 依赖于werkzeug,则仍需要安装werkzeug
    • 或者,在导入时重命名:from module1 import A as B
    【解决方案2】:

    除了@unwind's answer之外,通常的做法是保护模块中的代码,只有在模块直接使用时才应该运行:

    if __name__ == "__main__":
        <code to only execute if module called directly>
    

    这样就可以正常导入模块了。

    【讨论】:

    • 如果你对模块没有控制权,以至于你不能让它看起来像这样,你就是SOL。总是这样做。
    【解决方案3】:

    如果您只是对打印语句感到恼火,您可以将代码的输出重定向到不可见的地方,就像这篇文章的一条评论中解释的那样:http://coreygoldberg.blogspot.com/2009/05/python-redirect-or-turn-off-stdout-and.html

    sys.stdout = open(os.devnull, 'w')
    # now doing the stuff you need
    ...
    
    # but do not forget to come back!
    sys.stdout = sys.__stdout__
    

    文档:http://docs.python.org/library/sys.html#sys.stdin

    但是如果你想停用文件修改或耗时的代码,我唯一想到的就是一些肮脏的技巧:将你需要的对象复制到另一个文件中,然后导入它(但我不推荐它!)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-19
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2022-12-09
      • 2012-12-16
      • 1970-01-01
      相关资源
      最近更新 更多