代码之家  ›  专栏  ›  技术社区  ›  amit

如何在python中导入模块的一部分?

  •  4
  • amit  · 技术社区  · 14 年前

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

    class A:
      def f1():
      ...
    
    print "Done"
    ...
    

    我只需要类A的功能。但是,当我导入模块时,底部的代码(打印和其他)将被执行。有办法避免吗?基本上我需要导入一个模块的一部分:“从模块1导入一个”应该只导入一个。有可能吗?

    3 回复  |  直到 14 年前
        1
  •  11
  •   unwind    14 年前

    是的,当然:

    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.
    
        2
  •  2
  •   Joël    13 年前

    如果只对print语句感到恼火,可以将代码的输出重定向到不可见的地方,如本文的一条评论所述: 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

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

        3
  •  0
  •   Community CDub    7 年前

    除了 @unwind's answer 通常的方法是保护模块中的代码,该代码只有在直接与以下组件一起使用时才应运行:

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

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