问题引入:
写自动化测试工具的时候, 用了thinter实现简单的界面,以实现,交互显示和设置配置项,显示动态测试过程中日志,“开始测试”按钮触发这个整个自动化测试流程。
因为整个自动化测试是测试的【一个客户端】,中间是会底层利用win32api启动【这个客户端】的。
最后发现:当整个测试完成后,按X按钮关闭测试UI的时候,需测试的客户端又被启动了。 看日志发现是,整个测试流程又开始走一遍。 最后发现是if __name__=="__main__"引起的。
详细说下:

如上图所以问题。在pychorm中并不会出现问题,只有当打包编译成exe后运行,关闭UI后出现重复运行的情况。
问题验证:
创建文件mymain.py(相当于上面画图举例的文件a.py)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/8/28 16:25
# @Author : lishenluo
import threading
import mytt
from tkinter import *
def ui_start():
win = Tk()
# 设置标题
win.title("我是测试")
win.geometry("300x200+100+100")
button = Button(win, text='我是按钮', font=('Arial', 12), width=12, height=1, command=button_function)
button.pack()
win.mainloop()
def button_function():
th = threading.Thread(target=mytt.start, args=())
th.start()
if __name__=="__main__":
ui_start()
创建文件mytt.py(相当于上面画图举例的文件b.py)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/8/28 16:24
# @Author : lishenluo
import logging
logging.basicConfig(filename="test.log", filemode="w",
format="[%(asctime)s][%(name)s][%(levelname)s]%(message)s",
datefmt="%Y-%m-%d %H:%M:%S", level=logging.DEBUG)
logging.info("this is before if __name__:%s"%__name__)
def start():
logging.info("你是大笨蛋") #整个自动化测试开始入口函数
if __name__=='__main__':
start()
logging.info("this is after if __name__:%s"%__name__)
在pycharm运行结果,X关闭窗口后日志也不变,说明没有多余的运行。

利用pyinstaller编译出exe,对应mymain.spec文件如下
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['mymain.py','mytt.py'],
pathex=['E:\\JQCode\\jqtests\\threadUiTest'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='threadUITest',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=False )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='threadUITest')
利用cmd,去到对应目录下,编译出exe文件

最后pycharm代码目录结构,编译出的exe文件在dist下

运行并查看日志:

452



被折叠的 条评论
为什么被折叠?



