Python基础-main
Python基础-_main_
写在前面
如非特别说明,下文均基于
Python3
一、__main__的官方解释
参考 _main_ -- Top-level script environment
'_main_' is the name of the scope in which top-level code executes. A module’s _name_ is set equal to '_main_' when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own _name_, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:
if __name__ == "__main__":
# execute only if run as a script
main()
For a package, the same effect can be achieved by including a _main_.py module, the contents of which will be executed when the module is run with -m.
__main__是顶层代码执行环境的名字。当一个模块从标准输入,脚本或者解释器提示行中被读取时,模块的__name__属性被设置成__main__。
模块可以依据检查__name__属性是否为__main__的方式自我发现是否在main scope中,这允许了一种在模块中条件执行代码的常见用法,当模块作为脚本或者使用python -m命令运行时执行,而被导入时不执行:
if __name__ == "__main__":
# 当且仅当模块作为脚本运行时执行main函数
main()
对于包而言,可以在包中包含一个名为__main__.py的模块到达相同的效果,当模块使用python -m命令运行时,__main__py模块的内容会被执行。
二、__main__实践
第一节中说过,当模块从标准输入,脚本或者解释器命令行中被读取时,其__name__属性被设置为__main__ ,导入时值为模块名字。那么就可以根据这两种不同情况执行不同的代码。
Make a script both importable and executable
让脚本即可执行又可被导入,是对__main__这一特性最好的诠释:
def test():
print('This is test method in com.richard.other') def main():
test() if __name__ == '__main__': print('直接运行时,__name__属性:', __name__)
main()
else:
# 导入时被执行
print('导入时,__name__属性:', __name__)
直接运行时,输出:
直接运行时,__name__属性: __main__
This is test method in com.richard.other
导入时,输出:
>>> import com.richard.other.test as ctest
导入时,__name__属性: com.richard.other.test
>>>
这样,可以在if __name__ == '__main__':的判断下加入对这个模块的测试代码,就可以在不影响外部模块引用该模块的条件下,调试我们的模块了。
NOTICE: 示例在python 3+解释器中成功运行,的模块名为test.py,其包结构如下:

目录sublime已加入python解释器sys.path变量中。
For a package, the same effect can be achieved by including a _main_.py module, the contents of which will be executed when the module is run with -m.
Python基础-main的更多相关文章
- python之最强王者(2)——python基础语法
背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...
- python基础之循环结构以及列表
python基础之编译器选择,循环结构,列表 本节内容 python IDE的选择 字符串的格式化输出 数据类型 循环结构 列表 简单购物车的编写 1.python IDE的选择 IDE的全称叫做集成 ...
- 改写《python基础教程》中的一个例子
一.前言 初学python,看<python基础教程>,第20章实现了将文本转化成html的功能.由于本人之前有DIY一个markdown转html的算法,所以对这个例子有兴趣.可仔细一看 ...
- python基础——单元测试
python基础——单元测试 如果你听说过“测试驱动开发”(TDD:Test-Driven Development),单元测试就不陌生. 单元测试是用来对一个模块.一个函数或者一个类来进行正确性检验的 ...
- python基础——调试
python基础——调试 程序能一次写完并正常运行的概率很小,基本不超过1%.总会有各种各样的bug需要修正.有的bug很简单,看看错误信息就知道,有的bug很复杂,我们需要知道出错时,哪些变量的值是 ...
- python基础——错误处理
python基础——错误处理 在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因.在操作系统提供的调用中,返回错误码非常常见.比如打开文件的函数 ...
- python基础——filter函数
python基础——filter函数 Python内建的filter()函数用于过滤序列. 和map()类似,filter()也接收一个函数和一个序列.和map()不同的是,filter()把传入的函 ...
- Python自动化 【第七篇】:Python基础-面向对象高级语法、异常处理、Scoket开发基础
本节内容: 1. 面向对象高级语法部分 1.1 静态方法.类方法.属性方法 1.2 类的特殊方法 1.3 反射 2. 异常处理 3. Socket开发基础 1. ...
- Python基础学习笔记(十一)函数、模块与包
参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-functions.html 3. http://www.liao ...
随机推荐
- Docker问题方案收集
1.问题: Unable to connect to unix:///var/run/docker.sock (Permission denied) from PHP code 解决方法: Make ...
- 107、TensorFlow变量(三)
创建秩为1的张量 # create a rank1 tensor object import tensorflow as tf mystr = tf.Variable(["Hello&quo ...
- Html5 学习笔记 --》html基础 css 基础
HTML5 功能 HTML5特点 <!DOCTYPE html> <html lang="zh-cn"> <head> <meta cha ...
- 数据结构C语言实现
顺序表实现 typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Po ...
- 转 什么是Mbps、Kbps、bps、kb、mb及其换算和区别
Mbps 即 Milionbit pro second(百万位每秒): Kbps 即 Kilobit pro second(千位每秒): bps 即 bit pro second(位每秒): 速度单位 ...
- for,while,do while语句区别以及常见死循环格式
1.三种循环语句的区别: do...while循环至少执行一次循环体. 而for,while循环必须先判断条件是否成立,然后决定是否执行循环体语句. for循环和while循环的区别: 如果你想在循环 ...
- 一步一步学Vue(九) 路由元数据
一步一步学Vue(九):https://www.cnblogs.com/Johnzhang/p/7260888.html
- 41.Validate Binary Search Tree(判断是否为二叉搜索树)
Level: Medium 题目描述: Given a binary tree, determine if it is a valid binary search tree (BST). Assu ...
- 面试题。线程pingpong的输出问题
第一种情况:public class Main { public static void main(String args[]) { Thread t = new Thread() { public ...
- c# 编程--方法(函数)
方法(函数) 能够独立完成某项功能的模块 函数的四要素:函数名.输入.输出.函数体 函数定义.函数的调用 函数就是将一堆代码进行重用的一种机制,函数就是一段代码,这段代码可能有输入的值(参 ...