如何在Python中导入模块的一部分?
我需要使用一个Python模块(在某个库里可以找到)。这个模块长这样:
class A:
def f1():
...
print "Done"
...
我只需要类A的功能。但是,当我导入这个模块时,底部的代码(打印和其他的)也会被执行。有没有办法避免这种情况?基本上,我想只导入模块的一部分:像这样“from module1 import A”,这样只导入A。这样做可以吗?
3 个回答
0
除了@unwind的回答,通常的做法是把模块中那些只在直接使用模块时才需要运行的代码保护起来,方法是使用:
if __name__ == "__main__":
<code to only execute if module called directly>
这样你就可以正常导入这个模块了。
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
不过,如果你想停用文件修改或者耗时的代码,我想到的唯一办法就是用一些小技巧:把你需要的对象复制到另一个文件里,然后再导入它(但我不推荐这样做!)。
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.