编写“仅执行"代码的最佳实践是什么? Python模块?

编写“仅执行

问题描述:

我有一个Python模块,该模块专门用于作为脚本运行,绝不作为应导入的东西运行,我想在我的代码中强制执行(并传达)这一意图.

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

或在开始时中止

if __name__ != '__main__':
    exit()

# All the code in the module

可能带有警告

if __name__ != '__main__':
    print('You should not import this')
    exit()

# All the code in the module

甚至是断言

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

但我不确定从样式上或技术上哪个合适(如果有).

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

您确实可以做到

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.

相反,您应该将在启动时执行的代码放入函数(main()?)中,并以通常的方式执行.

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