[Python] 纯文本查看 复制代码# -*- coding:utf-8 -*-
import psutil # 要额外安装,判断程序是否运行
from time import sleep
import uiautomation # 要额外安装,操控窗口控件
import os
def ifProcessRunning(process_name='WeChat.exe'):
# 判断某个程序是否在运行
# 原理:获取正在运行程序的pid,通过pid获取程序名,再按程序名进行判断
pl = psutil.pids()
result = "PROCESS_IS_NOT_RUNNING"
for pid in pl:
if (psutil.Process(pid).name() == process_name):
if isinstance(pid, int):
result = "PROCESS_IS_RUNNING"
return result
def wechatlogin():
uiautomation.uiautomation.TIME_OUT_SECOND = 2 # global time out
if ifProcessRunning()=="PROCESS_IS_RUNNING":
try:
wechatWindow = uiautomation.WindowControl(searchDepth=1, className='WeChatMainWndForPC', Name='微信')
wechatWindow.Restore()
wechatWindow.Minimize()
except:
try:
uiautomation.PaneControl(searchDepth=1, ClassName='WeChatLoginWndForPC', Name='微信').ButtonControl(Name='仅传输文件')
except:
pass
os.system('taskkill /F /im "WeChat.exe" >nul')
os.startfile(WeChat_path)
loginwin = uiautomation.PaneControl(searchDepth=1, ClassName='WeChatLoginWndForPC', Name='微信')
try:
loginwin.ButtonControl(Name='进入微信').Click()
except:
loginwin.ButtonControl(Name='登录').Click()
else:
os.startfile(WeChat_path)
loginwin = uiautomation.PaneControl(searchDepth=1, ClassName='WeChatLoginWndForPC', Name='微信')
try:
loginwin.ButtonControl(Name='进入微信').Click()
except:
loginwin.ButtonControl(Name='登录').Click()
uiautomation.uiautomation.TIME_OUT_SECOND = 20 # global time out
wechatWindow = uiautomation.WindowControl(searchDepth=1, className='WeChatMainWndForPC', Name='微信')
sleep(10)
try:
wechatWindow.Minimize()
except:
pass
def wechatmsg(send_to='微信用户名',msg='要发送的消息'):
uiautomation.uiautomation.TIME_OUT_SECOND = 20
wechatWindow = uiautomation.WindowControl(searchDepth=1, className='WeChatMainWndForPC', Name='微信')
try:
wechatWindow.Restore()
except:
pass
wechatWindow.MoveToCenter()
wechatWindow.SetTopmost(True)
# sleep(2)
wechatWindow.EditControl(Name="搜索").Click()
wechatWindow.EditControl(Name="搜索").SendKeys(f'{send_to}{{enter}}', 0.5)
wechatWindow.EditControl(Name=send_to).SendKeys(msg,0.03)
wechatWindow.ButtonControl(Name="发送(S)").Click()
wechatWindow.SetTopmost(False)
wechatWindow.Minimize()
def wechatquit():
if ifProcessRunning()=="PROCESS_IS_RUNNING":
os.system('taskkill /F /im "WeChat.exe" >nul')
if __name__ == '__main__':
WeChat_directory = 'D:\soft\WeChat'
WeChat_path= os.path.join(WeChat_directory, 'WeChat.exe')
wechatlogin()
wechatmsg(send_to='微信收信用户名张三',msg='要发送的消息')
wechatmsg(send_to='李四', msg='要发送的消息')
# wechatquit()