0

Consider the two following files:

test.py:

import sys

def testfunction(string):
    print(string)

sys.exit(0)

test2.py:

from test import testfunction

testfunction("string")

I would expect the import of testfunction not to execute statements outside of that function, e.g., sys.exit(0). Why is this happening, and how can I prevent it?

user196994
  • 13
  • 2
  • besides the answers given, that are right, you can also arrange all your functions as methods of some outer class. The class code is executed, but not the def inner code blocks. – progmatico Feb 22 '18 at 15:18

2 Answers2

2

Quite simply:

# test.py
import sys

def testfunction(string):
    print(string)

if __name__ == "__main__":
    sys.exit(0)

The magic variable __name__ is set either to the module name (when the file is imported as a module) or to "__main__" when it's executed as a script.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Thanks. If one intends to import a function from a source file, there is no way in the example above to avoid the sys.exit() call except by modifying that source file to include this `__name__` check? – user196994 Feb 22 '18 at 17:25
  • well you could wrap the import in a try/except block and catch the SystemExit exception. But fixing the problem at the source (and contributing it back if it's oss) would probably be better. – bruno desthuilliers Feb 22 '18 at 20:30
  • Err well, no it actually won't work :-/ – bruno desthuilliers Feb 23 '18 at 12:32
0

Put everything you don't want to be executed under the condition

if __name__ == '__main__':
    ...
    sys.exit(0)
Sagar B Hathwar
  • 536
  • 6
  • 18