前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于Python中的__main__和编程模板

关于Python中的__main__和编程模板

作者头像
生信宝典
发布2018-02-05 15:22:41
1.7K0
发布2018-02-05 15:22:41
举报
文章被收录于专栏:生信宝典生信宝典

在python程序中经常可以看到 if__name__ == ' _ _ main _ _'的判定,下面来解释下。

首先在python交互式界面中输入以下程序,然后运行。

代码语言:javascript
复制
print(__name__)

得到的结果为:

代码语言:javascript
复制
__main__

简单的说,每当运行一个python脚本的时候,都会自动生成一个variable__name__

如果直接运行此脚本,__name__ 的值则自动为 __main__。若果此脚本是在其它脚本中被作为一个包导入运行的 (每个python脚本都可以直接作为一个包来使用),__name__的值会自动为其所在文件的文件名。

通过下例来帮助理解。在名为test1.py的脚本中输入以下:

代码语言:javascript
复制
if __name__ == '__main__':
    print('The __name__ is:', __name__, 'which means you are running the script directly')
else:
    print('The __name__ is:', __name__, 'which means you are running the script from importing')

首先运行此程序,结果为:

代码语言:javascript
复制
The __name__ is: __main__ which means you are running the module directly

然后在另一个脚本中(如果不熟悉PYTHONPATH环境变量,则在同一个目录运行)中输入:

代码语言:javascript
复制
import test1

运行此module后结果为:

代码语言:javascript
复制
The __name__ is: test1 which means you are running the module from importing

因此,if__name__ == ' _ _ main _ _':可用来限定脚本读取的环境,从而保证该脚本在做为包被导入时不会直接启动程序的执行。

提供个Python的模板

代码语言:javascript
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import division, with_statement
'''
Copyright 2017, 生信宝典  
===========================================================
'''
__author__ = 'SXBD'
__author_email__ = 'train@ehbioc.om'
#=========================================================

# 程序描述,会在运行时输出
desc = '''
Program description:

'''

# 导入常用包
import sys
import os
from time import localtime, strftime 
timeformat = "%Y-%m-%d %H:%M:%S"
from optparse import OptionParser as OP

# 并行运行时使用
#from multiprocessing.dummy import Pool as ThreadPool

# 解析网页时使用
#from bs4 import BeautifulSoup

# 出现编码错误时使用
#reload(sys)
#sys.setdefaultencoding('utf8')

# 全局变量,用于调试
debug = 0

# 命令行参数
def cmdparameter(argv):
    if len(argv) == 1:
        global desc
        print >>sys.stderr, desc
        cmd = 'python ' + argv[0] + ' -h'
        os.system(cmd)
        sys.exit(1)
    usages = "%prog -i file"
    parser = OP(usage=usages)
    parser.add_option("-i", "--input-file", dest="filein",
        metavar="FILEIN", help="")
    parser.add_option("-n", "--number", dest="number",
        type="int", help="Supply an int number")
    parser.add_option("-v", "--verbose", dest="verbose",
        action="store_true", help="Show process information")
    parser.add_option("-D", "--debug", dest="debug",
        default=False, action="store_true", help="Debug the program")
    (options, args) = parser.parse_args(argv[1:])
    assert options.filein != None, "A filename needed for -i"
    return (options, args)
#--------------------------------------------------------------------

def main():
    options, args = cmdparameter(sys.argv)
    #-----------------------------------
    file = options.filein
    verbose = options.verbose
    global debug
    debug = options.debug
    #-----------------------------------
    if file == '-':
        fh = sys.stdin
    else:
        fh = open(file)
    #--------------------------------
    for line in fh:
        pass
    #-------------END reading file----------
    #----close file handle for files-----
    if file != '-':
        fh.close()
    #-----------end close fh-----------
    ###--------multi-process--并行使用----------------
    #pool = ThreadPool(5) # 5 represents thread_num
    #result = pool.map(func, iterable_object)
    #pool.close()
    #pool.join()
    ###--------multi-process------------------
    if verbose:
        print >>sys.stderr,            "--Successful %s" % strftime(timeformat, localtime())

if __name__ == '__main__':
    startTime = strftime(timeformat, localtime())
    main()
    endTime = strftime(timeformat, localtime())
    # 运行日志记录
    fh = open('python.log', 'a')
    print >>fh, "%s\n\tRun time : %s - %s " %         (' '.join(sys.argv), startTime, endTime)
    fh.close()
    ###---------profile the program--程序运行慢时的检测-------
    #import profile
    #profile_output = sys.argv[0]+".prof.txt")
    #profile.run("main()", profile_output)
    #import pstats
    #p = pstats.Stats(profile_output)
    #p.sort_stats("time").print_stats()
    ###---------profile the program---------精品回顾画图三字经 生信视频 生信系列教程 心得体会 癌症数据库 高通量分析 Linux Python 在线画图
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-01-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 生信宝典 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档