更新时间:2023-12-04 22:50:40
来自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