您的位置:首页 > 其它

py windows一些封装函数

2014-02-12 15:52 381 查看

1.启动和杀死进程

1)启动exe
python中经常会遇到一些函数混淆不清楚

如os.system, os.popen,subprocess.popen

下面,我们来一一介绍

os.system 会得到返回值

os.popen 只会得到执行结果而没有返回值

当然也可以使用commands的命令同时得到返回值和执行结果,但是这个命令渐渐被废弃

returncode=os.system('cat /home/test')
output=os.popen('cat /home/test')
print output.read()
(status, output) = commands.getstatusoutput('cat /home/test')


python引入subprocess.Popen,相当厉害的一个函数,覆盖了所有想要实现的功能

subprocess主要是用来代替以下的模块和函数

os.system

os.spawn*

os.popen*

popen2.*

commands.*

首先,subprocess.call代替os.system,

subprocess.check_output代替os.popen

而subprocess.Popen则是最为全面的一个函数,它包含了stdin,stdout,stderr三个管道,args输入参数等等

plus.py

a = int(raw_input())
b = int(raw_input())

print 'a + b = ', a+b


python command line

import subprocess

p =subprocess.Popen('python C://plus.py', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

p.stdin.write('4\n')
p.stdin.write('5\n')

print p.stdout.readline()


也可以通过cmd,启动exe

def WinStartProcess(exeName,params=""):
cmd = exeName + " " + params
try:
win32api.WinExec(cmd)
except:
return False
return True

2)杀死进程

1. pskill 进程号 杀死进程

2. taskkill 命令较为常见, 可以根据应用程序名称来杀死进程

TASKKILL [/S system [/U username [/P [password]]]] { [/FI filter] [/PID processid | /IM imagename] } [/F] [/T]

/S system 指定要连接到的远程系统。

/U [domain\]user 指定应该在哪个用户上下文

执行这个命令。

/P [password] 为提供的用户上下文指定密码。如果忽略,提示输入。

/F 指定要强行终止的进程。

/FI filter 指定筛选进或筛选出查询的的任务。

/PID process id 指定要终止的进程的PID。

/IM image name 指定要终止的进程的图像名。通配符 '*'可用来指定所有图像名。

/T Tree kill: 终止指定的进程和任何由此启动的子进程。

/? 显示帮助/用法。

taskkill /f /im python.exe /t

3. processshacker可以杀死杀毒软件的进程,较为强大,自行查找

2.查找 程序 是否运行

一般情况下在windows中使用WMI,WMI是提供操作系统核心接口的管理支持技术

查找程序是否运行就是用这种技术

python中主要是利用win32com.client的dispatch函数

service = win32com.client.Dispatch('WbemScripting.SWbemLocator')
server = service.ConnectServer('127.0.0.1', 'root\cimv2', '', '')


具体代码如下

def WinIsAlive(processname):
pos = processname.find('.')
if pos == -1:
procname = processname + '.exe'
else:
procname = processname
service = win32com.client.Dispatch('WbemScripting.SWbemLocator') server = service.ConnectServer('127.0.0.1', 'root\cimv2', '', '')
ps = server.ExecQuery('select * from Win32_Process')
exist = 0
for p in ps:
if (p.Name.upper() == procname.upper()):
del service
return True
del service
return False


3.操作注册表

操作注册表的方式有两种,一种是通过python的内置模块_winreg,另一种方式就是Win32 Extension For Python的win32api模块

这里我们介绍 _winreg

操作动作可以包括 读取,创建,删除(key or value)

#直接通过键名读取键值
key =_winreg.OpenKey(_winreg.HKEY_CURRENT_USER,r"SOFTWARE\SogouGame")
value,type =_winreg.QueryValueEx(key,"")
value,type =_winreg.QueryValueEx(key,"Version")

#否则,遍历枚举
try:
i=0
while 1:
#EnumValue方法用来枚举键值,EnumKey用来枚举子键
name,value,type = _winreg.EnumValue(key,i)
print repr(name),value,type
i+=1
exceptWindowsError:
print

4.获取窗口句柄

通常使用win32gui模块来处理这个问题

1)获取当前所有窗口的句柄,窗口名和类名

##@函数目的: 枚举窗口的回调函数
##@参数说明:
##@返回值:  窗口句柄、窗口名和窗口类名
##@函数逻辑:
def windowEnumerationHandler(hwnd, resultList):
resultList.append((hwnd, win32gui.GetWindowText(hwnd),win32gui.GetClassName(hwnd)))

def windowChildEnumerationHandler(hwnd, resultList):
resultList.append((hwnd, win32gui.GetWindowText(hwnd), win32gui.GetClassName(hwnd)))

##@函数目的: 获取系统中所有窗口列表
##@参数说明:className:窗口类名;windowname:窗口名;level:搜索的深度,默认为2。
##@返回值:找到的窗口列表。形式为[(句柄,类名,窗口名),...]
##@函数逻辑:  递归搜索窗口列表,默认可以获取2层。例如搜狗浏览器主框架句柄和侧边栏句柄
def EnumAllWindows(level=2):
topWindows = []
win32gui.EnumWindows(windowEnumerationHandler, topWindows)
findResult = []
try:
for oneWnd in topWindows:
handle = oneWnd[0]
EnumAllChildWindows(handle,findResult,level)
except Exception, e:
None
return findResult

##@函数目的:    获取一个窗口的子窗口
##@函数参数:   resultList:子窗口列表;level:获取的子窗口级数。level值越大,则搜索深度越大
##@参数说明:
##@返回值:
def EnumAllChildWindows(handle,resultList,level):
hlist = []
if level == 0:
return
try:
resultList.append((handle,win32gui.GetClassName(handle),win32gui.GetWindowText(handle)))
win32gui.EnumChildWindows(handle,windowChildEnumerationHandler,hlist)
for cw in hlist:
EnumAllChildWindows(cw[0],resultList,level-1)
except:
None
2)再通过类名或者窗口名来定位句柄

def GetHandles(className="", wndName = ""):
windows = EnumAllWindows(3)
#f.write(str(windows))
handles = []
for window in windows:
if window[1].lower().find(className.lower()) != -1 and window[2].lower().find(wndName.lower()) != -1:
handles.append(window[0])
return handles


3)做些限制条件,得到specific窗口句柄

比如从子窗口限制

#通过类名递归搜索子窗体句柄
def SearchSubWindowByClassName(parentWindow,className,keyword2="",keyword3=""): #最多三个限制条件同时满足
#先判断窗口本身是不是要找的
try:
if parentWindow == 0:
return 0
ctrlClassName = win32gui.GetClassName(parentWindow)
if str(ctrlClassName).lower().find(str(className).lower()) != -1:
if str(ctrlClassName).lower().find(keyword2) != -1 and str(ctrlClassName).lower().find(keyword3) != -1:
return parentWindow
start = None
#如果有子窗口则循环每个子窗口
while True:
#对每个子窗口递归
start = FindSubWindow(parentWindow,start,None,None)
if start==0:
break
winHwnd = SearchSubWindowByClassName(start,className,keyword2,keyword3)
if winHwnd != 0:
return winHwnd
return 0
except:
return 0

def FindSubWindow(parentHwnd,startHwnd,className,windowName):
try:
return win32gui.FindWindowEx(parentHwnd,startHwnd,className,windowName)
except:
return 0


其实,不只是上面的方法可以获取handle,有多种方式可以获取handle,python可以灵活方便地处理windows窗口

5.鼠标

1)鼠标移动

def MouseTo(x,y):
win32api.SetCursorPos((x,y))


2)鼠标点击

def Click(mtype="LEFT"):
mtype = mtype.upper()
if mtype == "LEFT":
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0)
time.sleep(0.2)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)
elif mtype == "RIGHT":
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN,0,0,0,0)
time.sleep(0.2)
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP,0,0,0,0)
elif mtype == "MIDDLE":
win32api.mouse_event(win32con.MOUSEEVENTF_MIDDLEDOWN,0,0,0,0)
time.sleep(0.2)
win32api.mouse_event(win32con.MOUSEEVENTF_MIDDLEUP,0,0,0,0)


6.窗口位置和大小

获取窗口四个像素点的方法

def GetWindowRect(handle):
if handle == None or handle == 0:
return []
try:
return win32gui.GetWindowRect(handle)
except:
return []


返回一个list,包含四个数字,指相对屏幕0,0的位置,具体相对位置从下面的函数可以推敲出来

def GetStartPoint(handle, relativeX, relativeY):
rect = GetWindowRect(handle)
if relativeX == Position.LEFT:
x = rect[0]
elif relativeX == Position.RIGHT:
x = rect[2]
else:
x = (rect[0] / rect[2]) / 2

if relativeY == Position.TOP:
y = rect[1]
elif relativeY == Position.BOTTOM:
y = rect[3]
else:
y = (rect[1] / rect[3]) / 2
return (x, y)


另外,如果客户端软件全屏,则rect[0]和rect[1]会为负数,且为-8

但是不知道为毛 chrome 只有rect[0]为-1

def IsFullScreen(handle):
rect = GetWindowRect(handle)
return rect[0] <= 0 and rect[1] <= 0


http://www.cppblog.com/aurain/archive/2009/03/10/76126.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: