5

When I import a module in Python I usually proceed as follows:

from math import pi

pi

Answer -> 3.14159265

Is there any way that one could create a module that just after imported prints something?

For example:

import module

Answer -> Hello world!
Eugene S
  • 6,709
  • 8
  • 57
  • 91
KKKK
  • 53
  • 1
  • 3
  • 4
    Modules are executed by default when they are imported. This is why most are protected by `if __name__ == '__main__':` to _prevent_ this happening. – roganjosh Dec 02 '16 at 11:09
  • 3
    Although it's possible by adding simple print statement to your module, it's very bad design. Consider e.g. someone importing your module and wondering why there's your output. – infotoni91 Dec 02 '16 at 11:11

1 Answers1

6

Just add the print statement in your module and you will achieve exactly what you describe.

To follow up on your comment this is how your module should look like:

print 'hello'
#Here define functions of the module 
...

if __name__ == "__main__":     
    print 'world'              

Here you can find more info on this syntax: What does if __name__ == "__main__": do?

Community
  • 1
  • 1
FLab
  • 7,136
  • 5
  • 36
  • 69
  • Works fantastic! And any way it could print different messages deppending on how you open the file? For example: if you are in python command line -> import module -> it prints "hello". if you are in your system console and do -> python module.py -> it prints "world!" – KKKK Dec 02 '16 at 11:55
  • Everything works fantastic. Thank you very very much. – KKKK Dec 02 '16 at 12:14