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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With