设为首页 收藏本站
查看: 947|回复: 0

[经验分享] 从python run 和python unittest两种eclipse运行方式深入理解if __name__ == "__main__"

[复制链接]
累计签到:2 天
连续签到:1 天
发表于 2015-12-2 07:57:15 | 显示全部楼层 |阅读模式
  在写一个简单的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"]["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,那么将不会执行到后面的逻辑。
  
  到此,开始的疑问也就解决掉了!

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-146042-1-1.html 上篇帖子: python 抓取动态网页 下篇帖子: 如何把python最小化安装在客户机上面
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表