Python中if __name__ == "__main__": 的作用

在很多python脚本中在最后的部分会执行一个判断语句if __name__ == "__main__:",之后还可能会有一些执行语句。那添加这个判断的目的何在?

在python编译器读取源文件的时候会执行它找到的所有代码,而在执行之前会根据当前运行的模块是否为主程序而定义变量__name__的值为__main__还是模块名。因此,该判断语句为真的时候,说明当前运行的脚本为主程序,而非主程序所引用的一个模块。这在当你想要运行一些只有在将模块当做程序运行时而非当做模块引用时才执行的命令,只要将它们放到if __name__ == "__main__:"判断语句之后就可以了。

具体举个栗子方便理解:

# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")
# file two.py
import one        # start executing one.py

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

当运行python one.py,输出:

top-level in one.py
one.py is being run directly

当运行python two.py,输出:

top-level in one.py
one.py is being imported into another module
top-level in one.py
func() in one.py
two.py is being run directly


关于Python中if __name__ == '__main__':的问题

04-13

您好,请教一个很初级的python问题:rn我在研究BitTorrent的时候自己写了一段代码,存入testMain.py这个文件:rn#!/usr/bin/env pythonrn# -*- coding: cp936 -*-rnrn# Written by Bram Cohenrn# see LICENSE.txt for license informationrnrnimport sysrnsys.path.append('D:\develop\Python\BitTorrent-3.3\BitTorrent')rnsys.path.append('D:\develop\Python\BitTorrent-3.3')rnrnfrom sys import argvrnfrom BitTorrent.parseargs import parseargs, formatDefinitionsrnrndefaults = [rn ('piece_size_pow2', 18,rn "which power of 2 to set the piece size to"),rn ('comment', '',rn "optional human-readable comment to put in .torrent"),rn ('target', '',rn "optional target file for the torrent")rn ]rnrnif __name__ == '__main__':rn if len(argv) < 3:rn print 'usage is -'rn print argv[0] + ' file trackerurl [params]'rn printrn print formatDefinitions(defaults, 80)rn else:rn try:rn config, args = parseargs(argv[3:], defaults, 0, 0)rn print 'config',configrn print 'args',argsrn except ValueError, e:rn print 'error: ' + str(e)rn print 'run with no args for parameter explanations'rnrn我觉得我的问题应该很初级,但是我确实没看到相关资料,只在Python编程宝典时看到了这样一段描述的话:rn从if __name__ == '__main__':往下的代码是通用于许多GUI程序的一项约定。该行检测名称空间是否为rn“__main__”,并在条件成立(即为文件调用了解释器)的前提执行后续语句。如果文件作为一个模块导入,rn该条件就不成立,如果程序单独运行,而非作为模块在另一个程序中使用,后续语句就会执行。rnrn我现在的问题是,如何才能使程序单独运行,或者如何才能使程序在shell下单独运行,并且输入我的程序参数。rnrn我作了以下尝试:rn>>> import testMainrn>>> dir()rn['__builtins__', '__doc__', '__name__', 'argv', 'defaults', 'formatDefinitions', 'parseargs', 'sys', 'testMain']rn>>> testMainrnrn>>> testMain arg01 arg02rnSyntaxError: invalid syntaxrn>>> testMainrnrn>>> testMain [arg01,arg02]rnrnTraceback (most recent call last):rn File "", line 1, in -toplevel-rn testMain [arg01,arg02]rnNameError: name 'arg01' is not definedrn>>> testMain ['','']rnrnTraceback (most recent call last):rn File "", line 1, in -toplevel-rn testMain ['','']rnTypeError: unsubscriptable objectrn>>> testMain [myfile, http://myfile/announce]rnSyntaxError: invalid syntaxrn>>> testMain ['myfile.txt', 'http://myfile/announce']rnrnTraceback (most recent call last):rn File "", line 1, in -toplevel-rn testMain ['myfile.txt', 'http://myfile/announce']rnTypeError: unsubscriptable objectrn>>> rnrn都没能找到在命令行调用该模块的方式rn请指教

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试

关闭