简体   繁体   English

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

[英]How to import part of a module in python?

I need to use a python module (available in some library). 我需要使用python模块(在某些库中可用)。 The module looks like this: 该模块如下所示:

class A:
  def f1():
  ...

print "Done"
...

I need only the functionality of class A. However, when I import the module, the code at bottom (print and others) gets executed. 我只需要A类的功能。但是,当我导入模块时,底部的代码(print和其他)会被执行。 Is there a way to avoid that? 有没有办法避免这种情况? Essentially I need to import part of a module: "from module1 import A" which should import only A. Is it possible? 基本上我需要导入一个模块的一部分:“来自module1 import A”,它应该只导入A.是否可能?

Yes, sure: 是的,当然:

from module1 import A

Is the general syntax. 是一般语法。 For example: 例如:

from datetime import timedelta

The code at the bottom should be protected from running at import time by being wrapped like so: 应该保护底部的代码在导入时运行,方法如下:

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.

If you're only annoyed by the print statements, you could redirect the code's output to somewhere invisible, like explained in one comment of this post: http://coreygoldberg.blogspot.com/2009/05/python-redirect-or-turn-off-stdout-and.html 如果你只是对print语句感到烦恼,你可以将代码的输出重定向到不可见的地方,就像这篇文章的一篇评论中所解释的那样: http//coreygoldberg.blogspot.com/2009/05/python-redirect-or-关闭-标准输出,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__

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

But if you want to deactivate file modifications, or time-consuming code, the only thing that comes to my mind is some dirty trick: copy the objects you need in another file, then import it (but I do not recommend it!). 但是如果你想要停用文件修改或者耗费时间的代码,我唯一想到的就是一些肮脏的技巧:将你需要的对象复制到另一个文件中,然后导入它(但我不推荐它!)。

In addition to @unwind's answer the usual way of doing this is to protect the code in the module that should only be run if the module is used directly with: 除了@ unwind的回答之外 ,通常的做法是保护模块中的代码,只有在模块直接使用时才能运行:

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

That way you can import the module normally. 这样你就可以正常导入模块了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM