Abort execution of a module in Python

末鹿安然 提交于 2019-12-01 03:47:23

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()

My main.py looks like this,

print 'main 1'

try:
    import my_module
except ImportError:
    pass

print 'main 2'

and my_module.py looks like this,

print 'module 1'

if True:
    raise ImportError
else:
    pass

print 'module 2'

output is,

main 1
module 1
main 2

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

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

main()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!