[英]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. 我有一个Python模块,专门用于作为脚本运行,从不作为应该导入的东西,我想在我的代码中强制执行(和沟通)这个意图。
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. 但我不确定哪种(如果有的话)是合适的,风格上或技术上的。
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. 相反,你应该把在启动时执行的代码放到一个函数( main()
?)中并以通常的方式执行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.