当前位置:   article > 正文

Python PyWin32 模块_pypiwin32

pypiwin32

PyWin32是Python在Windows平台上的一个扩展库,提供了访问Windows API、COM接口和其他Windows原生功能的功能。它允许开发者使用Python语言来编写与Windows操作系统交互的应用程序。

通过PyWin32,开发者可以利用Python的简洁和灵活性,与Windows系统进行无缝交互,编写各种应用程序、脚本和自动化工具。无论是系统管理、GUI开发还是与其他Windows应用程序集成,PyWin32都提供了强大的功能和工具,使得Python在Windows平台上的应用开发更加便捷和高效。

该项目地址是:GitHub - mhammond/pywin32: Python for Windows (pywin32) Extensions

在Python安装路径下\AppData\Local\Programs\Python\Python38\Lib\site-packages 有帮助文档:PyWin32.chm

文件类API在模块win32file中,进程类API在模块win32process中,win32con定义了所有的常量,,一些难以分类的API则在模块win32api中(大部分是kernel32.dll导出的API)

ctypes 调用C库printf打印输出

  1. >>> import ctypes
  2. >>> # cdll = cdecl标准 windll = stdcall标准 linux则是调用 libc.so.6
  3. >>> msvcrt = ctypes.cdll.LoadLibrary("C:\WINDOWS\system32\msvcrt.dll")
  4. >>> msvcrt = ctypes.cdll.msvcrt
  5. >>>
  6. >>> string = "hello lyshark\n"
  7. >>> string = string.encode("utf-8")
  8. >>> msvcrt.printf(string)
  9. hello lyshark
  10. 14

ctypes 调用messagebox输出:

  1. >>> from ctypes import *
  2. >>> user32 = windll.LoadLibrary("user32.dll")
  3. >>> string = "Hello lyshark\n"
  4. >>> string = string.encode("utf-8")
  5. >>>
  6. >>>user32.MessageBoxA(0,string,"ctypes".encode("utf-8"),0)
  7. >>>
  8. >>>user32 = windll.LoadLibrary("user32.dll")
  9. >>>MessageBox = user32.MessageBoxA
  10. >>>print(MessageBox(0,"hello lyshark".encode("utf-8"),"msgbox".encode("utf-8"),0))

ctypes 调用 kernel32

  1. >>> kernel32 = windll.LoadLibrary("kernel32.dll")
  2. >>> CreateProcess = kernel32.CreateProcessA
  3. >>> ReadProcessMemory = kernel32.ReadProcessMemory

ctypes 声明结构体

  1. from ctypes import *
  2. class MyStruct(Structure):
  3. _fields_ = [
  4. ("username",c_char*10),
  5. ("age",c_int),
  6. ("sex",c_long)
  7. ]
  8. class MyUnion(Union):
  9. _fields_ = [
  10. ("a_long",c_long),
  11. ("a_int",c_int),
  12. ("a_char",c_char*10)
  13. ]
  14. MyStruct.username = "lyshark"
  15. MyStruct.age = 22
  16. print(MyStruct.username)

pywin32常用使用方式

  1. >>> import win32api
  2. >>> import win32con
  3. >>>
  4. >>> win32api.MessageBox(0,"hello lyshark","Msgbox",win32con.MB_OK)
  5. 1
  6. >>> import win32process
  7. # 打开记事本程序,获得其句柄
  8. >>> handle = win32process.CreateProcess('c:\\windows\\notepad.exe',
  9. '', None , None , 0 ,win32process. CREATE_NO_WINDOW , None , None ,
  10. win32process.STARTUPINFO())
  11. # 使用TerminateProcess函数终止记事本程序
  12. >>> win32process.TerminateProcess(handle[0],0)
  13. >>> import win32event
  14. # 创建进程获得句柄
  15. >>> handle = win32process.CreateProcess('c:\\windows\\notepad.exe',
  16. '', None , None , 0 ,win32process. CREATE_NO_WINDOW , None , None ,
  17. win32process.STARTUPINFO())
  18. # 等待进程结束
  19. >>> win32event.WaitForSingleObject(handle[0], -1)
  20. 0 # 进程结束的返回值
  21. >>> import win32api
  22. # 打开记事本程序,在后台运行,即显示记事本程序的窗口
  23. >>> win32api.ShellExecute(0, 'open', 'notepad.exe', '','',0)

鼠标控制

  1. import win32gui
  2. import win32api
  3. 获取句柄
  4. hwnd = win32gui.FindWindow(classname, titlename)
  5. 获取窗口左上角和右下角坐标
  6. left, top, right, bottom = win32gui.GetWindowRect(hwnd)
  7. 获取某个句柄的类名和标题
  8. title = win32gui.GetWindowText(hwnd)
  9. clsname = win32gui.GetClassName(hwnd)
  10. 获取父句柄hwnd类名为clsname的子句柄
  11. hwnd1= win32gui.FindWindowEx(hwnd, None, clsname, None)
  12. 获取位置
  13. win32api.GetCursorPos()
  14. 鼠标定位到(30,50)
  15. win32api.SetCursorPos([30,150])
  16. 执行左单键击,若需要双击则延时几毫秒再点击一次即可
  17. win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
  18. 右键单击
  19. win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP | win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0)
  20. 发送回车键
  21. win32api.keybd_event(13,0,0,0)
  22. win32api.keybd_event(13,0,win32con.KEYEVENTF_KEYUP,0)
  23. 关闭窗口
  24. win32gui.PostMessage(win32lib.findWindow(classname, titlename), win32con.WM_CLOSE, 0, 0)

鼠标左右键判断

  1. import win32api
  2. import win32con
  3. b = (0,0)
  4. # win32api.GetAsyncKeyState(win32con.VK_LMENU)
  5. # VK_LBUTTON 鼠标左键
  6. # VK_RBUTTON 鼠标右键
  7. # https://baike.baidu.com/item/GetAsyncKeyState/918387?fr=aladdin
  8. for i in range(100):
  9. a = win32api.GetCursorPos()
  10. if a != b:
  11. b = a
  12. print(a)
  13. else:
  14. print("xx")
  15. time.sleep(1)

将上面代码有趣的组合在一起,可以搞事情了,部分片段。

  1. def Write_Dictionaries(LogName,Dict):
  2. logging.basicConfig(level=logging.DEBUG,
  3. format = "%(asctime)s --> %(message)s",
  4. datefmt = "%Y-%m-%d %H:%M:%S",
  5. filename = LogName,
  6. filemode = "a+")
  7. logging.info(str(Dict))
  8. def RecordingScript(LogName,Sleep):
  9. temp = (0,0)
  10. mose = {"Pos_x":0, "Pos_y":0, "MouseL":0, "MouseR":0}
  11. while True:
  12. Position = win32api.GetCursorPos()
  13. MouseLeft = win32api.GetAsyncKeyState(win32con.VK_LBUTTON)
  14. MouseRight = win32api.GetAsyncKeyState(win32con.VK_RBUTTON)
  15. if Position != temp or MouseLeft!=0 or MouseRight!=0:
  16. temp = Position
  17. mose["Pos_x"] = Position[0]
  18. mose["Pos_y"] = Position[1]
  19. mose["MouseL"] = MouseLeft
  20. mose["MouseR"] = MouseRight
  21. Write_Dictionaries(LogName,mose)
  22. time.sleep(int(Sleep))
  23. def writelog():
  24. with open("aaa.log","r",encoding="utf-8") as fp:
  25. b = [ item.split(" --> ")[1] for item in fp.readlines()]
  26. for i in b:
  27. dic = eval(i.replace("\n",""))
  28. win32api.SetCursorPos(bos)
  29. print("坐标:{}".format(bos))

遍历进程模块

  1. import os,sys
  2. import win32api
  3. import win32con
  4. import win32process
  5. handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid ===> 10992 )
  6. hModule = win32process.EnumProcessModules(handle)
  7. temp=[]
  8. for i in hModule:
  9. print(win32process.GetModuleFileNameEx(handle,i))
  10. win32api.CloseHandle(handle)

调用createprocess

  1. CreateProcess调用
  2. appName:可执行的文件名。
  3. commandLine:命令行参数。
  4. processAttributes:进程安全属性,如果为None,则为默认的安全属性。
  5. threadAttributes:线程安全属性,如果为None,则为默认的安全属性。
  6. bInheritHandles:继承标志。
  7. dwCreationFlags:创建标志。
  8. newEnvironment:创建进程的环境变量。
  9. currentDirectory:进程的当前目录。
  10. startupinfo :创建进程的属性。
  11. WaitForSingleObject(handle, milisecond)
  12. handle : 要操作的进程句柄
  13. milisecond: 等待的时间,如果为-1,则一直等待.
  14. >>> import win32process
  15. >>> handle=win32process.CreateProcess("d://run.exe", '', None , None , 0 ,win32process.CREATE_NEW_CONSOLE , None , None ,win32process.STARTUPINFO())
  16. >>> win32event.WaitForSingleObject(handle[0],2)

枚举部分进程模块

  1. import win32process
  2. import win32api
  3. import win32con
  4. from ctypes import *
  5. import ctypes
  6. def GetProcessModules( pid ):
  7. handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid )
  8. hModule = win32process.EnumProcessModules(handle)
  9. temp=[]
  10. for i in hModule:
  11. temp.append([hex(i),win32process.GetModuleFileNameEx(handle,i)])
  12. win32api.CloseHandle(handle)
  13. return temp
  14. temp = GetProcessModules(5852)
  15. for x in temp:
  16. print("[+] 模块地址: {} ------> 模块名称: {}".format(x[0],x[1]))

取出进程PID

  1. handle = win32gui.FindWindow(0,ClassName)
  2. threadpid, procpid = win32process.GetWindowThreadProcessId(handle)
  3. ProcessModule = GetProcessModules(int(procpid))

枚举所有窗口句柄

  1. import win32gui
  2. hwnd_title = dict()
  3. def get_all_hwnd(hwnd,mouse):
  4. if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
  5. hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})
  6. win32gui.EnumWindows(get_all_hwnd, 0)
  7. for h,t in hwnd_title.items():
  8. print(h, t)

打开网页或文件

  1. win32api.ShellExecute(None, "open", "C:\\Test.txt", None, None, SW_SHOWNORMAL) # 打开C:\Test.txt 文件
  2. win32api.ShellExecute(None, "open", "http:#www.google.com", None, None, SW_SHOWNORMAL) # 打开网页www.google.com
  3. win32api.ShellExecute(None, "explore", "D:\\C++", None, None, SW_SHOWNORMAL) # 打开目录D:\C++
  4. win32api.ShellExecute(None, "print", "C:\\Test.txt", None, None, SW_HIDE) # 打印文件C:\Test.txt
  5. win32api.ShellExecute(None,"open", "mailto:", None, None, SW_SHOWNORMAL) # 打开邮箱
  6. win32api.ShellExecute(None, "open", "calc.exe", None, None, SW_SHOWNORMAL) # 调用计算器
  7. win32api.ShellExecute(None, "open", "NOTEPAD.EXE", None, None, SW_SHOWNORMAL) # 调用记事本

窗口句柄操作

  1. import time
  2. import win32gui
  3. import win32api
  4. import win32con
  5. """
  6. 该类实现了:查找(定位)句柄信息,菜单信息
  7. """
  8. class HandleMenu(object):
  9. def __init__(self, cls_name=None, title=None):
  10. self.handle = win32gui.FindWindow(cls_name, title)
  11. self.window_list = []
  12. def call_back(self, sub_handle, sub_handles): # Edit 20de0
  13. """遍历子窗体"""
  14. title = win32gui.GetWindowText(sub_handle)
  15. cls_name = win32gui.GetClassName(sub_handle)
  16. print(title, '+', cls_name)
  17. position = win32gui.GetWindowRect(sub_handle)
  18. aim_point = round(position[0] + (position[2] - position[0]) / 2), round(
  19. position[1] + (position[3] - position[1]) / 2)
  20. win32api.SetCursorPos(aim_point)
  21. time.sleep(1)
  22. # 鼠标点击
  23. # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)
  24. # time.sleep(0.05)
  25. # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)
  26. # time.sleep(0.05)
  27. # ComboBox - ---------
  28. # Edit - ---------
  29. if cls_name == 'ComboBox':
  30. win32gui.SendMessage(sub_handle, win32con.WM_SETTEXT, None, '902723')
  31. time.sleep(1)
  32. sub_handles.append({'cls_name': cls_name, 'title': title})
  33. return True
  34. def get_sub_handles(self):
  35. """通过父句柄获取子句柄"""
  36. sub_handles = []
  37. win32gui.EnumChildWindows(self.handle, self.call_back, sub_handles)
  38. print(sub_handles)
  39. return sub_handles
  40. def get_menu_text(self, menu, idx):
  41. import win32gui_struct
  42. mii, extra = win32gui_struct.EmptyMENUITEMINFO() # 新建一个win32gui的空的结构体mii
  43. win32gui.GetMenuItemInfo(menu, idx, True, mii) # 将子菜单内容获取到mii
  44. ftype, fstate, wid, hsubmenu, hbmpchecked, hbmpunchecked, \
  45. dwitemdata, text, hbmpitem = win32gui_struct.UnpackMENUITEMINFO(mii) # 解包mii
  46. return text
  47. def get_menu(self):
  48. """menu操作(记事本)"""
  49. menu = win32gui.GetMenu(self.handle)
  50. menu1 = win32gui.GetSubMenu(menu, 0) # 第几个菜单 0-第一个
  51. cmd_ID = win32gui.GetMenuItemID(menu1, 3) # 第几个子菜单
  52. win32gui.PostMessage(self.handle, win32con.WM_COMMAND, cmd_ID, 0)
  53. menu_text1 = [self.get_menu_text(menu, i) for i in range(5)]
  54. menu_text2 = [self.get_menu_text(menu1, i) for i in range(9)]
  55. print(menu_text1)
  56. print(menu_text2)
  57. def get_all_window_info(self, hwnd, nouse):
  58. # 去掉下面这句就所有都输出了,但是我不需要那么多
  59. if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
  60. # 设置为最前窗口
  61. win32gui.SetForegroundWindow(hwnd)
  62. # 获取某个句柄的标题和类名
  63. title = win32gui.GetWindowText(hwnd)
  64. cls_name = win32gui.GetClassName(hwnd)
  65. d = {'类名': cls_name, '标题': title}
  66. info = win32gui.GetWindowRect(hwnd)
  67. aim_point = round(info[0] + (info[2] - info[0]) / 2), round(info[1] + (info[3] - info[1]) / 2)
  68. win32api.SetCursorPos(aim_point)
  69. time.sleep(2)
  70. self.window_list.append(d)
  71. def get_all_windows(self):
  72. """获取所有活动窗口的类名、标题"""
  73. win32gui.EnumWindows(self.get_all_window_info, 0)
  74. return self.window_list
  75. if __name__ == '__main__':
  76. # 1.通过父句柄获取子句柄
  77. # hm=HandleMenu(title='另存为')
  78. # hm.get_sub_handles()
  79. # 2.menu操作
  80. # hm=HandleMenu(title='aa - 记事本')
  81. # hm.get_menu()
  82. # 3.获取所有活动窗口的类名、标题
  83. hm = HandleMenu()
  84. hm.get_all_windows()

鼠标操作

  1. import win32api
  2. import win32gui
  3. import win32con
  4. import win32print
  5. import time
  6. # 1 获取句柄
  7. # 1.1 通过坐标获取窗口句柄
  8. handle = win32gui.WindowFromPoint(win32api.GetCursorPos()) # (259, 185)
  9. # 1.2 获取最前窗口句柄
  10. handle = win32gui.GetForegroundWindow()
  11. # 1.3 通过类名或查标题找窗口
  12. handle = win32gui.FindWindow('cls_name', "title")
  13. # 1.4 找子窗体
  14. sub_handle = win32gui.FindWindowEx(handle, None, 'Edit', None) # 子窗口类名叫“Edit”
  15. # 句柄操作
  16. title = win32gui.GetWindowText(handle)
  17. cls_name = win32gui.GetClassName(handle)
  18. print({'类名': cls_name, '标题': title})
  19. # 获取窗口位置
  20. info = win32gui.GetWindowRect(handle)
  21. # 设置为最前窗口
  22. win32gui.SetForegroundWindow(handle)
  23. # 2.按键-看键盘码
  24. # 获取鼠标当前位置的坐标
  25. cursor_pos = win32api.GetCursorPos()
  26. # 将鼠标移动到坐标处
  27. win32api.SetCursorPos((200, 200))
  28. # 回车
  29. win32api.keybd_event(13, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0)
  30. win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0)
  31. # 左单键击
  32. win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
  33. # 右键单击
  34. win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP | win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0)
  35. # 鼠标左键按下-放开
  36. win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
  37. win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
  38. # 鼠标右键按下-放开
  39. win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
  40. win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
  41. # TAB键
  42. win32api.keybd_event(win32con.VK_TAB, 0, 0, 0)
  43. win32api.keybd_event(win32con.VK_TAB, 0, win32con.KEYEVENTF_KEYUP, 0)
  44. # 快捷键Alt+F
  45. win32api.keybd_event(18, 0, 0, 0) # Alt
  46. win32api.keybd_event(70, 0, 0, 0) # F
  47. win32api.keybd_event(70, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键
  48. win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0)
  49. # 3.Message
  50. win = win32gui.FindWindow('Notepad', None)
  51. tid = win32gui.FindWindowEx(win, None, 'Edit', None)
  52. # 输入文本
  53. win32gui.SendMessage(tid, win32con.WM_SETTEXT, None, '你好hello word!')
  54. # 确定
  55. win32gui.SendMessage(handle, win32con.WM_COMMAND, 1, btnhld)
  56. # 关闭窗口
  57. win32gui.PostMessage(win32gui.FindWindow('Notepad', None), win32con.WM_CLOSE, 0, 0)
  58. # 回车
  59. win32gui.PostMessage(tid, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0) # 插入一个回车符,post 没有返回值,执行完马上返回
  60. win32gui.PostMessage(tid, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
  61. print("%x" % win)
  62. print("%x" % tid)
  63. # 选项框
  64. res = win32api.MessageBox(None, "Hello Pywin32", "pywin32", win32con.MB_YESNOCANCEL)
  65. print(res)
  66. win32api.MessageBox(0, "Hello PYwin32", "MessageBox", win32con.MB_OK | win32con.MB_ICONWARNING) # 加警告标志

针对PDF处理

  1. from win32con import SW_HIDE, SW_SHOWNORMAL
  2. for fn in ['2.txt', '3.txt']:
  3. print(fn)
  4. res = win32api.ShellExecute(0, # 指定父窗口句柄
  5. 'print', # 指定动作, 譬如: open、print、edit、explore、find
  6. fn, # 指定要打开的文件或程序
  7. win32print.GetDefaultPrinter(),
  8. # 给要打开的程序指定参数;GetDefaultPrinter  取得默认打印机名称 <type 'str'>,GetDefaultPrinterW  取得默认打印机名称 <type 'unicode'>
  9. "./downloads/", # 目录路径
  10. SW_SHOWNORMAL) # 打开选项,SW_HIDE = 0; {隐藏},SW_SHOWNORMAL = 1; {用最近的大小和位置显示, 激活}
  11. print(res) # 返回值大于32表示执行成功,返回值小于32表示执行错误
  12. # 打印 -pdf
  13. def print_pdf(pdf_file_name):
  14. """
  15. 静默打印pdf
  16. :param pdf_file_name:
  17. :return:
  18. """
  19. # GSPRINT_PATH = resource_path + 'GSPRINT\\gsprint'
  20. GHOSTSCRIPT_PATH = resource_path + 'GHOSTSCRIPT\\bin\\gswin32c' # gswin32c.exe
  21. currentprinter = config.printerName # "printerName":"FUJI XEROX ApeosPort-VI C3370\""
  22. currentprinter = win32print.GetDefaultPrinter()
  23. arg = '-dPrinted ' \
  24. '-dBATCH ' \
  25. '-dNOPAUSE ' \
  26. '-dNOSAFER ' \
  27. '-dFitPage ' \
  28. '-dNORANGEPAGESIZE ' \
  29. '-q ' \
  30. '-dNumCopies=1 ' \
  31. '-sDEVICE=mswinpr2 ' \
  32. '-sOutputFile="\\\\spool\\' \
  33. + currentprinter + " " + \
  34. pdf_file_name
  35. log.info(arg)
  36. win32api.ShellExecute(
  37. 0,
  38. 'open',
  39. GHOSTSCRIPT_PATH,
  40. arg,
  41. ".",
  42. 0
  43. )
  44. # os.remove(pdf_file_name)

截屏

  1. from PIL import ImageGrab
  2. # 利用PIL截屏
  3. im = ImageGrab.grab()
  4. im.save('aa.jpg')
  5. # 5.文件的读写
  6. import win32file, win32api, win32con
  7. import os
  8. def SimpleFileDemo():
  9. testName = os.path.join(win32api.GetTempPath(), "opt_win_file.txt")
  10. if os.path.exists(testName):
  11. os.unlink(testName) # os.unlink() 方法用于删除文件,如果文件是一个目录则返回一个错误。
  12. # 写
  13. handle = win32file.CreateFile(testName,
  14. win32file.GENERIC_WRITE,
  15. 0,
  16. None,
  17. win32con.CREATE_NEW,
  18. 0,
  19. None)
  20. test_data = "Hello\0there".encode("ascii")
  21. win32file.WriteFile(handle, test_data)
  22. handle.Close()
  23. # 读
  24. handle = win32file.CreateFile(testName, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
  25. rc, data = win32file.ReadFile(handle, 1024)
  26. handle.Close() # 此处也可使用win32file.CloseHandle(handle)来关闭句柄
  27. if data == test_data:
  28. print("Successfully wrote and read a file")
  29. else:
  30. raise Exception("Got different data back???")
  31. os.unlink(testName)
  32. if __name__ == '__main__':
  33. SimpleFileDemo()
  34. # print(win32api.GetTempPath()) # 获取临时文件夹路径
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/137724
推荐阅读
相关标签
  

闽ICP备14008679号