How to import part of a module in python?
I need to use a python module (available in some library). 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. 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?
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
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
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:
if __name__ == "__main__":
<code to only execute if module called directly>
That way you can import the module normally.
精彩评论