python对第3方软件进行操作,可以采用下面的方式。
1 win32,PyAutoGUI安装
pip install pypiwin32
pip install PyAutoGUI
2 操作方式
- 打开软件(如果软件已打开,需要先关闭)
- 进行操作
- 关闭软件
代码如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import psutil
import os
import win32api
import win32con
import time
deactivate_time = 20
exe_path = r'C:Program FilesNotepad++notepad++.exe'
process_name = "notepad++.exe"
def exe_is_active():
"""
判断"notepad++.exe"进程是否存在
:return: 进程存在,返回False,否则为True
"""
processes_name = []
pids = psutil.pids()
for pid in pids:
p = psutil.Process(pid)
processes_name.append(p.name())
if process_name in processes_name:
print('{} is active.'.format(process_name))
return True
else:
print('{} is not active.'.format(process_name))
return False
if __name__ == '__main__':
if exe_is_active():
# 终止进程
os.system(r'taskkill /F /IM {}'.format(process_name))
time.sleep(2)
else:
# 打开软件
print('Open {}'.format(process_name))
os.startfile(exe_path)
time.sleep(5)
print('Start:')
# 模拟键盘输入ctrl+r
# ctrl键位码是17
win32api.keybd_event(17, 0, 0, 0)
time.sleep(1)
# r键位码是86
win32api.keybd_event(82, 0, 0, 0)
time.sleep(1)
# 释放按键
win32api.keybd_event(82, 0, win32con.KEYEVENTF_KEYUP, 0)
time.sleep(1)
win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
# 等待执行结束
print('Wait {}s'.format(deactivate_time))
time.sleep(deactivate_time)
# 终止进程
print('Kill {}'.format(process_name))
os.system(r'taskkill /F /IM {}'.format(process_name))
3 如果软件不能关闭,需要将第3方软件置顶,采用下面代码:
hwnd = win32gui.FindWindow(None, 'xx.exe')
# hwnd = win32gui.FindWindow('xx.exe', None)
# 窗口需要正常大小且在后台,不能最小化
win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
# 窗口需要最大化且在后台,不能最小化
# ctypes.windll.user32.ShowWindow(hwnd, 3)
win32gui.SetForegroundWindow(hwnd)
time.sleep(2)
4 通过定位坐标进行按键操作
# 50, 350为目标对象的坐标
pyautogui.moveTo(50, 350, duration=0.2, tween=pyautogui.easeInOutQuad)
pyautogui.click(clicks=1)
参考:
PyAutoGUI
Python win32gui SetAsForegroundWindow function not working properly
https://stackoverflow.com/questions/42370339/python-3-6-install-win32api/42400980