OSError: [WinError -2147221008] 尚未调用 CoInitialize

ealte 2019-05-09 12:46:59
Python写Monkey代码中,总是提示报错,
Can not load UIAutomationCore.dll.
You may need to install Windows Update KB971513.
https://github.com/yinkaisheng/WindowsUpdateKB971513ForIUIAutomation
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "E:/PythonTest/WoniuCBT_FrameWorkV1/mokeytesting/smart_monkey.py", line 94, in start_test
self.random_press()
File "E:/PythonTest/WoniuCBT_FrameWorkV1/mokeytesting/smart_monkey.py", line 69, in random_press
x, y= self.random_pos()
File "E:/PythonTest/WoniuCBT_FrameWorkV1/mokeytesting/smart_monkey.py", line 25, in random_pos
pygame.Rect = window.BoundingRectangle #生成上下左右边界位置 生成Rect对象
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\uiautomation\uiautomation.py", line 5324, in BoundingRectangle
rect = self.Element.CurrentBoundingRectangle
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\uiautomation\uiautomation.py", line 5635, in Element
self.Refind(maxSearchSeconds=TIME_OUT_SECOND, searchIntervalSeconds=self.searchWaitTime)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\uiautomation\uiautomation.py", line 5855, in Refind
if not self.Exists(maxSearchSeconds, searchIntervalSeconds, False if raiseException else DEBUG_EXIST_DISAPPEAR):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\uiautomation\uiautomation.py", line 5805, in Exists
control = FindControl(self.searchFromControl, self._CompareFunction, self.searchDepth, False, self.foundIndex)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\uiautomation\uiautomation.py", line 7614, in FindControl
control = GetRootControl()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\uiautomation\uiautomation.py", line 7397, in GetRootControl
return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.GetRootElement())
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\uiautomation\uiautomation.py", line 50, in instance
cls._instance = cls()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\uiautomation\uiautomation.py", line 61, in __init__
raise ex
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\uiautomation\uiautomation.py", line 56, in __init__
self.IUIAutomation = comtypes.client.CreateObject("{ff48dba4-60ef-4201-aa87-54103eef594e}", interface=self.UIAutomationCore.IUIAutomation)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\comtypes\client\__init__.py", line 238, in CreateObject
obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\comtypes\__init__.py", line 1225, in CoCreateInstance
_ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p))
File "_ctypes/callproc.c", line 918, in GetResult
OSError: [WinError -2147221008] 尚未调用 CoInitialize。


不知道什么原因,请各位大虾帮忙看看?
# -*- coding: utf-8 -*-
from comtypes import CoInitialize, CoUninitialize
from pymouse import PyMouse
from pykeyboard import PyKeyboard
import uiautomation,random,time,os
from PIL import ImageGrab
import os,time,subprocess
import threading,win32gui
import pygame


#创建一只聪明的猴子
class MokeyTestSmart:

def __init__(self):
self.mouse = PyMouse()
self.keyboard = PyKeyboard()
self.sleep_time = 0.5

#生成随机坐标
def random_pos(self):
#利用UIAutomation获取窗口位置,然后依据这个值生成随机坐标,确保我们的monkey所有操作都是在应用窗口内完成
window = uiautomation.WindowControl(searchDepth=1, ClassName='Notepad')

pygame.Rect = window.BoundingRectangle #生成上下左右边界位置 生成Rect对象
#生成当前窗口内的坐标
x = random.randint(pygame.Rect.left, pygame.Rect.right) #对应left right top bottom
y = random.randint(pygame.Rect.top, pygame.Rect.bottom)

self.mouse.move(x, y)
return x, y

#模拟鼠标单击操作
def random_click(self):
x, y = self.random_pos()
self.mouse.click(x,y)

print("在位置[%d:%d]进行单击操作."%(x,y))
time.sleep(self.sleep_time)

#模拟鼠标双击操作
def random_double_click(self):
x, y = self.random_pos()
self.mouse.click(x=y,y=y,button=1,n=2)

print("在位置[%d:%d]进行双击操作."%(x,y))
time.sleep(self.sleep_time)

#模拟鼠标右击操作
def random_right_click(self):
x, y = self.random_pos()
self.mouse.click(x,y,2)

print("在位置[%d:%d]进行右键操作."%(x,y))
time.sleep(self.sleep_time)

#模拟随机输入
def random_input(self):
x, y=self.random_pos()
content = ['Woniuxy','abcedef','Good Afternoon','Automation','123456','123.45','2019-01-13']
random_content = self.get_random_list(content)
self.mouse.click(x,y)
self.keyboard.type_string(random_content) #输入文字信息
print("在位置[%d:%d]处输入内容:%s"%(x,y,random_content))
time.sleep(self.sleep_time)

#模拟随机按键操作
def random_press(self):
x, y= self.random_pos()
key_list = [self.keyboard.end_key,self.keyboard.control_key,self.keyboard.alt_key,self.keyboard.backspace_key]
random_key = self.get_random_list(key_list)
self.keyboard.press_key(random_key)
self.keyboard.release_key(random_key)
print("在位置[%d:%d]处进行按键操作."%(x,y))
time.sleep(self.sleep_time)

#启动一个应用程序,并完成Monkey测试
def start_test(self,execute,count):
# 执行命令时,使用"start /b"表示在后台运行,不阻塞运行线程
os.system("start /b "+ execute)
time.sleep(5)
for i in range(count):
# 生成一个随机数,用于决定运行哪个操作
seed = random.randint(0,count)
if seed <= count * 0.2:
self.random_click()
elif seed <= count * 0.4:
self.random_double_click()
elif seed <= count * 0.6:
self.random_input()
elif seed <= count * 0.8:
self.random_right_click()
else:
self.random_press()
#停止进程
os.system("taskkill /f /im note.exe")

#公共调用函数 针对list随机取值
def get_random_list(self,args):
random_index = random.randint(0,10000)%len(args)
return args[random_index]

#间隔一定时间来截图,检查进程,并且窗口置顶
def check_runtime(self,interval):
time.sleep(10)
while True:
tasklist = str(subprocess.check_output("tasklist"))
if "notepad.exe" in tasklist:
print("检查进程:程序还在运行中。")
try:
# win32gui.FindWindow(window)
window = uiautomation.WindowControl(searchDepth=1,ClassName="Notepad")
uiautomation.SetForegroundWindow(win32gui.FindWindow("Notepad",None))

except:
print('检查进程:程序已停止运行.')
break
#截图
now = time.strftime("%Y%m%d_%H%M%S",time.localtime())
screen_path = os.path.join(os.getcwd(),'screenshot\\%s_monkey.png'%now)
ImageGrab.grab().save(screen_path)
time.sleep(3)
else:
print("检查进程:程序已停止运行.")
break

if __name__ == '__main__':

monkey = MokeyTestSmart()
time.sleep(2)
# monkey.start_test('notepad.exe',1)
threads = []
threads.append(threading.Thread(target=monkey.start_test,args=('notepad.exe',2)))
threads.append(threading.Thread(target=monkey.check_runtime,args=(2,)))

CoInitialize()
for t in threads:
t.setDaemon(True) #设置子线程为守护线程
CoInitialize()
t.start()
for t in threads:
t.join() #阻塞主线程,让主线程阻塞总时长=其中运行最长时间的子线程的时长

print("主线程执行结束。")








...全文
774 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧