What's the best practice for writing an “execu

2019-08-10 19:32发布

问题:

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__':
    print('You should not import this')
    exit()

# All the code in the module

or even an assertion

assert __name__ == '__main__', 'You should not import this'

But I'm not sure which (if any) is appropriate, stylistically or technically.

回答1:

While you indeed can do

if __name__ != '__main__':
    raise ImportError(...)
    # or maybe just emit a warning

it may stand in your feet the other day.

At least, you should keep the functions, classes and other definitions alone - they don't do any harm and maybe you or someone else needs them later.

If you import a module which just exposes functions and classes and values without doing output or other things, all you lose is some milliseconds.

Instead, you should put the code which executes on startup into a function (main()?) and execute that in the usual manner.