繁体   English   中英

Python的执行流程

[英]Python flow of execution

有人能解释一下python程序的执行流程,尤其是关于main函数的流程吗? 如果将其与C的执行进行比较和对比将会有所帮助。

当你执行“python myprog.py”时,python interpeter将逐行开始运行脚本:

import os #import the os module
print "prints somthing"
def f(num): ... # define a function

a = 5 / 2.0 # calculating stuff stuff ... 
if __name__ == '__main__': #__name__ is '__main__' only if this was the file that was started by the interpeter
    f(a) #calling the function f...

在C中,有一个特殊的功能“main”将在启动时执行。 这个(如上所述对于python不适用)

没有深入,在c中你有一个特定的“入口”功能(主要):

int main() {
    // stuff
}

编译此函数,可执行文件将以它开头。

在python中,您通常会加载一个特定的模块(类似于python mymodule.py )并通过检查__name__的值来验证main-ness:

if "__main__" == __name__:
    print "this is main"

__name__变量通常是模块的名称( "mymodule.py" ),当它是你加载的主模块时会有例外(然后它会自动设置为"__main__" )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM