如何确定python脚本是作为模块导入还是作为脚本运行? [英] how do I determine whether a python script is imported as module or run as script?
问题描述
这个问题很简单,但没有通过搜索回答.如何在python脚本中确定此脚本是作为模块导入还是作为脚本运行? python有什么区别吗?
The question is rather straightforward but not answered by searching. How do I determine in a python script whether this script is imported as a module or run as a script? Is there a difference at all in python?
问题是,仅当作为脚本运行时,我才想评估命令行参数,如果仅导入模块以在另一个脚本中使用它,则不希望. (我希望能够同时使用一个脚本作为库和程序.)恐怕最有效的方法是建立lib和使用它的第二个脚本,但是我想为小型工具提供第二个选择. /libs.
The problem is, that I want to evaluate the command line parameters only if run as a script, but not if the module is only imported to use it in another script. (I want to be able to use one script as both library and program.) I am afraid the vanilla way would be to build the lib and a second script that uses it, but I'd like to have a second option for small tool/libs.
推荐答案
来自python 文档:
使用以下命令运行Python模块时
When you run a Python module with
python fibo.py
python fibo.py
模块中的代码将为
被执行,就像您导入它一样
但__name__
设置为
"__main__"
.这意味着通过添加
此代码在您的模块末尾:
the code in the module will be
executed, just as if you imported it,
but with the __name__
set to
"__main__"
. That means that by adding
this code at the end of your module:
if __name__ == '__main__':
# Running as a script
您可以将文件用作脚本以及可导入的模块,因为解析命令行的代码仅在将模块作为主"文件执行时才运行
you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the "main" file
这篇关于如何确定python脚本是作为模块导入还是作为脚本运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!