What's the best practice for writing an “execute only” Python module?
问题 I have a Python module that is intended exclusively for running as a script and never as something that should be imported, and I'd like to enforce (and communicate) that intention in my code. What is the best practice for accomplishing this? I can imagine a few options such as wrapping the whole file in if __name__ == '__main__': # All the code in the module or aborting at the start if __name__ != '__main__': exit() # All the code in the module perhaps with a warning if __name__ != '__main__