pywinauto connect 连接软件之 循环查找PID

650 阅读1分钟

python中使用 pywinauto.connect 连接软件时,需要查找软件.exe 文件的 内存PID。

但有些软件有多个同名 .exe 在内存中,只是PID不同。例如:WXWork.exe

解决方法:

1、先获取  WXWork.exe  在内存中所有的PID。

2、用for 循环去逐一连接程序。

示例:

#coding=utf-8

import win32clipboard as wc
import win32con
from pywinauto.application import *
from PIL import ImageGrab
import time
from psutil import process_iter


class WeiXin(object):
    def __init__(self):
        wxPath = r"E:\Program Files (x86)\WXWork\WXWork.exe"
        self.app = Application().start(wxPath)
        self.pid = self.__get_pid()
        print(self.pid)
        if self.pid == False:
            print("请登录企业微信!")
            return

        # 准备连接软件
        for i, item in enumerate(self.pid):
            print('正在连接软件...')
            try:
                self.app.connect(path=wxPath, process=item)
                self.weixin_window = self.app.window(class_name="WeWorkWindow")
                self.weixin_window.set_focus()
            except Exception as e:
                print('Error>>', e)
                continue
            else:
                print('连接软件成功!')
                break

        self.weixin_window.move_window(0, 0)
        self.weixin_window.draw_outline(colour='red')  # 在窗口周围画一个轮廓。


    def start_chat(self):
        pic = ImageGrab.grab()
        pic.save('screen.png')

    def __get_pid(self):
        PID = process_iter()
        name = ''
        pid_num = 0
        pid_arry = []
        for pid_temp in PID:
            #print(pid_temp)
            pid_dic = pid_temp.as_dict(attrs=['pid', 'name'])
            if pid_dic['name'] == 'WXWork.exe':
                name = pid_dic['name']
                pid_num = pid_dic['pid']
                pid_arry.append(pid_num)
        if len(pid_arry):
            return pid_arry
        else:
            return False


if __name__ == '__main__':
    weixin = WeiXin()
    weixin.start_chat()