Skip to content Skip to sidebar Skip to footer

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 tes

Solution 1:

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 = Trueif 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 = Trueif some_condition:
        returnprint(' module2')

_my_whole_freaking_module()

Solution 2:

My main.py looks like this,

print'main 1'try:
    import my_module
except ImportError:
    passprint'main 2'

and my_module.py looks like this,

print'module 1'ifTrue:
    raise ImportError
else:
    passprint'module 2'

output is,

main1
module 1main2

Solution 3:

You can wrap the module code inside function, like this:

defmain():
  print(' module1')
  some_condition=Trueif some_condition:
    returnprint(' module2')

main()

Post a Comment for "Abort Execution Of A Module In Python"