zoukankan      html  css  js  c++  java
  • Python main 函数

    Python 中 main 语句的作用整理:

    1、Python 语句中可以不包含主函数 main 函数;

    2、if __name__=='__main__' 语句是为了自我调试代码方便,作为执行程序的入口,在 Python 脚本作为 module 被 import 时该语句下代码不运行;

    下面编写两个测试代码:print_test.pyprint_test_module.dy

    print_test.py (这里的 main 部分可以没有)如下:

     1 import datetime
     2 print('Hello World')
     3 print('Time is',datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
     4 print('__name__ value: ', __name__) 
     5 
     6 def main():
     7     print('This is main function')
     8     
     9 if __name__=='__main__':
    10     #main()
    11     print('HaHa')
    12    

    print_test_module.py 如下:

    1 import print_test
    2 print('将print_test.py作为module导入执行')

    单独运行 print_test.py 时,结果如下:

    1 Hello World
    2 Time is 2021-08-24 15:48:54
    3 __name__ value:  __main__
    4 HaHa

    单独运行 prin_test_module.py 时,结果如下:

    1 Hello World
    2 Time is 2021-08-24 15:53:48
    3 __name__ value:  print_test
    4 将print_test.py作为module导入执行

    对比两段程序运行结果可发现,当直接运行包含 main 函数的程序时,main 函数会被执行,同时程序的__name__变量值为'__main__'。

    当包含有 main 函数的程序 print_test.py 被作为 module 被 import 时,print_test_module.py 对应的__name__变量值为该 module 对应的函数名称 print_test,因此 print_test.py 中的 main 函数不会被执行。

    若想在 print_test_module.py 中也执行 main 函数,则需要添加语句:print_test.main(),即

     1 import print_test
     2 print('将print_test.py作为module导入执行')
     3 print_test.main()
     4 
     5 结果:
     6 Hello World
     7 Time is 2021-08-24 15:56:59
     8 __name__ value:  print_test
     9 将print_test.py作为module导入执行
    10 This is main function

    可以看到,main 函数就执行了。

  • 相关阅读:
    windows sharepoint service 适配器 使用说明
    Windows SharePoint Services 适配器 启动工作流失败的解决方案。
    编写一个SharePoint 自定义Web服务
    任意输入三个数,获得最大值
    用ASP获取别的网页的内容
    k8s搭建web界面管理rancher
    CRT 远程连接 ubuntu失败
    开源Nginx 文件上传服务器。ngx_upload_module+web.py+gevent+varnish前端缓存
    Esxi 5.1 添加存储设备的问题
    Abp Vnext 中如何统一接口返回值
  • 原文地址:https://www.cnblogs.com/lmj-sky/p/15180751.html
Copyright © 2011-2022 走看看