Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate importation of module non-fatally?

Tags:

python

import

I'd like use if __name__ != '__main__': and then end the execution of a script at that point when it's being imported, rather than doing the usual if __name__ == '__main__': and indentation of all the rest of the code in the file.

However I have been unable to determine what would cause only this to happen and not have other undesirable side-effects. sys.exit() stops the whole interpreter and all the other things I've tried either raise some sort of exception or are illegal.

Update:

I've selected @trutheality's answer because it accomplishes what I want and is extremely easy to start using. That said, I thought several of the other answers very interesting and/or clever -- thanks to all who responded -- and plan on investigating some of them further as time permits. I had no idea doing what I want could get so involved.

like image 499
martineau Avatar asked Sep 18 '25 06:09

martineau


1 Answers

Another Hack:

# code

if __name__ == "__main__": exec("""

# main code

#""")

So... you've lost the indentation, but also the syntax highlighting and any other features of the editor you were using, unless you comment out the if line every time you edit.

like image 131
trutheality Avatar answered Sep 19 '25 19:09

trutheality