Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abort execution of a module in Python

I'd like to stop evaluation of a module that is being imported, without stopping the whole program.

Here's an example of what I want to achieve:

main.py

print('main1')
import testmodule
print('main2')

testmodule.py

print(' module1')
some_condition=True
if some_condition:
  exit_from_module()  # How to do this?
print(' module2')     # This line is not executed.

Expected output:

main1
 module1
main2
like image 599
Oleh Prypin Avatar asked Jul 04 '11 12:07

Oleh Prypin


People also ask

How do you close a Python module?

Python sys module contains an in-built function to exit the program and come out of the execution process — sys. exit() function. The sys. exit() function can be used at any point of time without having to worry about the corruption in the code.

How do I stop a Python program after a certain time?

Python sleep() is a function used to delay the execution of code for the number of seconds given as input to sleep(). The sleep() command is a part of the time module. You can use the sleep() function to temporarily halt the execution of your code.

Why is Python running my module when I import it?

This happens because when Python imports a module, it runs all the code in that module. After running the module it takes whatever variables were defined in that module, and it puts them on the module object, which in our case is salutations .


1 Answers

There is no good way to stop execution of a module. You can raise an exception, but then your importing module will need to deal with it. Perhaps just refactor like this:

print(' module1')
some_condition = True
if not some_condition:
  print(' module2')

Update: Even better would be to change your module to only define functions and classes, and then have the caller invoke one of those to perform the work they need done.

If you really want to do all this work during import (remember, I think it would be better not to), then you could change your module to be like this:

def _my_whole_freaking_module():
    print(' module1')
    some_condition = True
    if some_condition:
        return
    print(' module2')

_my_whole_freaking_module()
like image 105
Ned Batchelder Avatar answered Sep 23 '22 22:09

Ned Batchelder