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

时间:2010-11-26 09:08:34

标签: python module import

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

class A:
  def f1():
  ...

print "Done"
...

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

3 个答案:

答案 0 :(得分:11)

是的,确定:

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.

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

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

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

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