python之如何启动一个应用程序

很多初学者会有这样的思考,通过python编写代码,如何启动一个python编写的应用程序呢?
有过c/c++开发的朋友都知道:c/c++程序都会有一个main函数作为程序的入口函数。python是c语言开发的,作为更高级的语言,肯定是也是参考c/c++的方式来启动程序。谈到这里就不能绕过__main__。

对__main__的英文介绍如下:

'_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:

中文含义是如下:

__main__是顶层代码执行环境的名字。当一个模块从标准输入,脚本或者解释器提示行中被读取时,模块的__name__属性被设置成__main__

模块可以依据检查__name__属性是否为__main__的方式自我发现是否在main scope中,这允许了一种在模块中条件执行代码的常见用法,当模块作为脚本或者使用python -m命令运行时执行,而被导入时不执行。

当一个脚本从标准输入或者解释器提示行中被读取时,模块的__name__属性就会被设置为__main__。当模块通过import方式导入时,则__name__属性是模块的名称,不会修改为__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__)

要启动一个python语言编写的程序,程序入口脚本一定要包含"if __name__ == '__main__'":语句。if后面的else可以添加也可以不添加,添加的好处是对于模块的一些自测代码可以考虑添加进去,这样通过else分支就可以实现对模块的功能的测试。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值