从python run 和python unittest两种eclipse运行方式深入理解if __name__ == "__main__"
在写一个简单的python测试程序的时候,发现eclipse中Run as "Python run 和 Python unittest”结果不一样?为什么会不一样?
先贴一下代码段:
# -*- coding: utf-8 -*-
'''
Created on 2015-1-28 @author: z.q.ot
'''
import unittest from driver import Driver
from new_plan_api import new_plan_check, new_plan_accept, new_plan_reject,\
plans_detail, plans_detail_today
import json
from unittest import runner new_plan_id_array = [] class Test(unittest.TestCase): def setUp(self):
print "setUp"
self.driver_info = Driver(usr='soil',pwd='soil',channel=1,typ=3)
self.token_id = self.driver_info.driver_login()
#self.new_plan_id_array = [] def tearDown(self):
print "tearDown" # @unittest.skip("not check new plan")
def testA_Check_new_plan(self): print "testCheck_new_plan......"
result = new_plan_check(self.token_id)
print result
JsonResult = json.loads(result,"utf-8");
if JsonResult["result"] == 0:
print "check new plan is success and the new plan count is: %d"%JsonResult["data"]["page"]["total"]
self.new_plan_count = JsonResult["data"]["page"]["total"]
for i in range(self.new_plan_count):
new_plan_id_array.append(JsonResult["data"]["rows"][i]["id"])
else:
print "check new plan is fail and result code is: %d"%JsonResult["result"] @unittest.skip("not accept new plan")
def testB_Accept_new_plan(self):
print "testAccept_new_plan......"
print new_plan_id_array
for i in new_plan_id_array:
print "new_plan_id is %d" % i
new_plan_accept(i, self.token_id)
# @unittest.skip("not Reject new plan")
# def testC_Reject_new_plan(self):
# print "testReject_new_plan......"
#new_plan_reject(plan_id=1, self.token_id)
# @unittest.skip("not get detail today")
def testD_detail_today(self):
print "Get today plans......"
plans_detail_today(self.token_id) def suite():
suite = unittest.TestSuite()
suite.addTest(Test("testD_detail_today"))
#suite.addTest(Test("testA_Check_new_plan"))
#suite.addTest(Test("testB_Accept_new_plan"))
return suite #or use like this
#tests=['testA_Check_new_plan','testB_Accept_new_plan','testD_detail_today']
#return unittest.TestSuite(map(Test,tests)) if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
#unittest.main()
runner = unittest.TextTestRunner()
runner.run(suite())
在eclipse中对此代码段进行调试,发现:
1,在python真正入口操作中有所不同,run方式会执行到main函数中,而python unittest不会执行到。
2,run方式会根据控制来执行对应的测试,而python unittest执行全部测试
其中,调试python unittest方式main函数进入如下函数:
def __get_module_from_str(self, modname, print_exception, pyfile):
""" Import the module in the given import path.
* Returns the "final" module, so importing "coilib40.subject.visu"
returns the "visu" module, not the "coilib40" as returned by __import__ """
try:
mod = __import__(modname)//入口就进入这里
for part in modname.split('.')[1:]:
mod = getattr(mod, part)
return mod
except:
......更多的代码查看源码pydev_runfiles.py
此时的modname为文件名:handle_new_plan_test;通过这样的查看,可知,在python unittest运行的时候,文件作为一个模块导入到了执行程序pydev_runfiles.py中。似乎有点说明一个问题:Python文件的执行有"导入执行”和“未导入执行(就是执行自身)“
还是有些迷糊?那么接下来的说明会更清晰。
因为程序执行的时候,总会有一个不同的地方,那就是上面说的那个问题。那么python到底是怎么去做模块导入执行和自身执行的呢?
贴一段测试代码:
#-*- coding: utf-8 -*- def sayHello():
print "hello" if __name__ == "__main__":
print "__main__"
sayHello()
python作为一种脚本语言,我们用python写得各个module都可以可以包含__main__,当然也可以不包含,主要的体现就在:
1,当单独执行此module时,会根据__main__中逻辑去执行,其结果为:
>>>
__main__
hello
>>>
2 , 当该module被其他的module引入使用时,其中的"if __name__ == "__main__":所表示的逻辑不会被执行,这是因为当被其他模块引用时,__name__的值将发生变化,其将是文件module的名字,如之前 __get_module_from_str()函数所获得modname,所以if条件为false,那么将不会执行到后面的逻辑。
到此,开始的疑问也就解决掉了!
从python run 和python unittest两种eclipse运行方式深入理解if __name__ == "__main__"的更多相关文章
- 「python」: arp脚本的两种方法
「python」: arp脚本的两种方法 第一种是使用arping工具: #!/usr/bin/env python import subprocess import sys import re de ...
- python中执行shell的两种方法总结
这篇文章主要介绍了python中执行shell的两种方法,有两种方法可以在Python中执行SHELL程序,方法一是使用Python的commands包,方法二则是使用subprocess包,这两个包 ...
- python中的pandas的两种基本使用
python中的pandas的两种基本使用2018年05月19日 16:03:36 木子柒努力成长 阅读数:480 一.pandas简介 pandas:panel data analysis(面板数据 ...
- python执行linux命令的两种方法
python执行linux命令有两种方法: 在此以Linux常用的ls命令为例: 方法一:使用os模块 1 2 3 shell# python >> import os >> ...
- python学习--python 连接SQLServer数据库(两种方法)
1. python 学习.安装教程参照: http://www.runoob.com/python/python-tutorial.html 2. 集成开发环境 JetBrains PyCharm C ...
- Pycharm上python和unittest两种姿势傻傻分不清楚
前言 经常有人在群里反馈,明明代码一样的啊,为什么别人的能出报告,我的出不了报告:为什么别人运行结果跟我的不一样啊... 这种问题先检查代码,确定是一样的,那就是运行姿势不对了,一旦导入unittes ...
- Pycharm上python和unittest两种姿势傻傻分不清楚【转载】
前言 经常有人在群里反馈,明明代码一样的啊,为什么别人的能出报告,我的出不了报告:为什么别人运行结果跟我的不一样啊... 这种问题先检查代码,确定是一样的,那就是运行姿势不对了,一旦导入unittes ...
- Python随机生成验证码的两种方法
Python随机生成验证码的方法有很多,今天给大家列举两种,大家也可以在这个基础上进行改造,设计出适合自己的验证码方法方法一:利用range Python随机生成验证码的方法有很多,今天给大家列举两种 ...
- python安装第三方包的两种方式
最近研究QQ空间.微博的(爬虫)模拟登录,发现都涉及RSA算法.于是需要下一个RSA包(第三方包).折腾了很久,主要是感觉网上很多文章对具体要在哪里操作写得不清楚.这里做个总结,以免自己哪天又忘了. ...
随机推荐
- js模块化开发
主要有两个:一个是sea.js,另一个是require.js
- lintcode:三数之和
题目 三数之和 给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组. 样例 如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集 ...
- PCB工艺镀金(电金)和沉金(化金)的区别
1.镀金和沉金的别名分别是什么? 镀金:硬金,电金(镀金也就是电金) 沉金:软金,化金 (沉金也就是化金) 2.别名的由来: 镀金:通过电镀的方式,使金粒子附着到pcb板上,所以叫电金,因为附着 ...
- 基于IDEA 最新Spirng3.2+hibernate4+struts2.3 全注解配置 登录
原文 基于IDEA 最新Spirng3.2+hibernate4+struts2.3 全注解配置 登录 首先说说 IDEA 12,由于myeclipse越来越卡,我改用idea12 了,发现其功能强悍 ...
- MultiSelectListPreference 的使用心得
最近在学习Android上的开发,打算做一个app.在做之前感觉很简单的功能,自己也有几年的C++经验,应该学起来很容易.但是事实告诉我,要注意的细节还是很多的. 大部分的app都会有设置页面, 用来 ...
- JS中用execCommand("SaveAs")保存页面兼容性问题解决方案
开发环境:ASP.NET MVC,其他环境仅供参考. 问题描述:在开发中遇到这样的需求,保存页面,通常使用JavaScript的saveAs进行保存,各浏览器对saveAs支持,见下表. 代码一:初始 ...
- linux系统启动级别
linux运行级别 以管理员身份进入Linux,修改文件:/etc/inittab 找到"id:5:initdefault:"其中的5就是X-window,为默认的运行级别 lin ...
- 最受欢迎的ASP.NET的CMS下载
1. Umbraco 项目地址 下载 Umbraco是一个开放源码的CMS内容管理系统,基于asp.net建立,使用mssql进行存储数据.使用Umbraco,设计师能创造出有效的XHTML标记模板和 ...
- MacOS安装phpMyAdmin几点问题
1. 登录时出现“#2002 无法登录 MySQL 服务器”. 原因: phpMyAdmin为PHP编写,MacOS默认安装的php配置,设置mysql监听socket默认为/var/mysql/my ...
- Python3 学习第二弹: 字符串String
字符串表示问题 常见用法 '' 与 "" 就不提了 一些特殊用法 三引号:接收多行字符串的输入 >>>print('''Oh my God!''') Oh my ...