如何让python模拟安卓模拟器 按键脚本本能输入到游戏

博客访问: 96847
博文数量: 40
博客积分: 2174
博客等级: 大尉
技术积分: 437
注册时间:
IT168企业级官微
微信号:IT168qiye
系统架构师大会
微信号:SACC2013
分类: Python/Ruby
python sendkeys 是一个很简单而支持包要求很少的开源包。对于一些由按键组成的控制可以方便的完成。
pywin32里的POSTMessage 可以以完成一部分直接的窗口消息发送,找到窗口句柄发送就行。对于复杂widows的内部消息机制有所了解会很方便使用。我所做的只是,给一些对话框发送,确定或取消的消息。免去了,模拟按键带来的对其它程序及用户使用的干扰但好像还是要把窗口移到前台再发送,后台发送我没有测试,但是对话框可能一出现就跑到前台来了。我也没办法了。
阅读(2206) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
请登录后评论。python能不能做游戏外挂_python吧_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:134,448贴子:
python能不能做游戏外挂收藏
如题。。。弱弱地。。。
基本不能。
错误.可以使用相关方法插入游戏线程, python对win32 debug支持很好
之所以说基本不能,就是因为这方法太复杂。没必要用python来浪费时间。
呃,,我也觉得复杂,那我还是用别的写吧哎。。。
C#行不行?对C不精通啊。。。
C#有点麻烦,C堪称强悍,懂C#害怕学不会C?
不复杂其实..
高人,请问有demo么?发给俺一下学习学习~~Email:
51CTO学院11年行业品牌,1400万用户选择,中国专业IT技能学习平台,python.通过在线学习的方式,帮助广大技术人员实现技能提升,高薪就业的职业梦想,python.
是用的第三方模块吗?没有觉得原生的python做这个有什么简单的。
做外挂,有不用第三方模块的吗
有一门语言叫做C,它有一个超集叫做C++。还有一门语言叫做汇编。如果仅说python,我还真没想出如果不用第三方模块,做外挂有什么容易的。不过话又说回来,外挂也有不同的级别,也许楼主要的很简单,用python的第三放模块能做也是有可能的。
不管你是用C、C++,还是汇编写外挂,都是调用别人写的API或者OS的API,关于这一点,什么语言都是一个样的,Python只是可以更快速的实现。
能不能快速实现我就不知道了,那个模块我又没有用过。我想说的是用合适的东西做合适的事情。外挂最好的选择还是C或者C++。
您的第三句和第四句是矛盾的,不解释。。。
我用python,除非python自己集成的,否则不愿安装第三方插件,如果python自己在发布时没有集成,那么我通常以为有一定的原因。最简单的解释就是不合适。
您用C/C++是不是也不用第三方的库呢
如非必要,非版本集成库,一概不用。因为要考虑到版本升级,没准就找不到第三方库对应的升级版本了。
这个可能是编程目标的问题。如果是应用级编程,使用第三方库越快越好。如果是系统级编程,可自由调配的资源越多越好。
回到主题。写外挂不像是系统级的吧
不像。不过写外挂需要掌握的东西,比应用级要高。如果仅仅要写外挂而不考虑其他东西,可以当我没说。
不同的应用都有其需要的特定的特定东西,没有高低之分。外挂仅仅是外挂,不是企业级的应用,没有那么多要考虑的。
那就换成多这个字吧。外挂繁琐在对数据的分析上。只是自己用就算了,要发布的话还需要升级维护。要做个好外挂复杂度不亚于企业级应用,
如此,那我可就疼了。。。。。不过,都感谢各位的指导哈~~谢谢~~谢谢~~
理论上能只要你是超级牛人。。。
C/C++要用100行代码,python要用上1000代码都不知道写完没
大神啊,都是大神啊,这都能扯,厉害。用易语言吧,免得你们说这复杂那复杂。黄泉客一定是大神。外挂都企业级和系统级了。高啊。
真它妈愚昧,你们所谓外挂基本就是调用windows API,这一点Python绝对没问题。而且可能开发时间还要短一些,代码也少。别忘了,python嵌入C语言也很简单!
登录百度帐号推荐应用
为兴趣而生,贴吧更懂你。或Python实现windows下模拟按键和鼠标点击的方法
我的图书馆
Python实现windows下模拟按键和鼠标点击的方法
## _*_ coding:UTF-8 _*_import win32apiimport win32conimport win32guifrom ctypes import *import timeVK_CODE = {&&'backspace':0x08,&&'tab':0x09,&&'clear':0x0C,&&'enter':0x0D,&&'shift':0x10,&&'ctrl':0x11,&&'alt':0x12,&&'pause':0x13,&&'caps_lock':0x14,&&'esc':0x1B,&&'spacebar':0x20,&&'page_up':0x21,&&'page_down':0x22,&&'end':0x23,&&'home':0x24,&&'left_arrow':0x25,&&'up_arrow':0x26,&&'right_arrow':0x27,&&'down_arrow':0x28,&&'select':0x29,&&'print':0x2A,&&'execute':0x2B,&&'print_screen':0x2C,&&'ins':0x2D,&&'del':0x2E,&&'help':0x2F,&&'0':0x30,&&'1':0x31,&&'2':0x32,&&'3':0x33,&&'4':0x34,&&'5':0x35,&&'6':0x36,&&'7':0x37,&&'8':0x38,&&'9':0x39,&&'a':0x41,&&'b':0x42,&&'c':0x43,&&'d':0x44,&&'e':0x45,&&'f':0x46,&&'g':0x47,&&'h':0x48,&&'i':0x49,&&'j':0x4A,&&'k':0x4B,&&'l':0x4C,&&'m':0x4D,&&'n':0x4E,&&'o':0x4F,&&'p':0x50,&&'q':0x51,&&'r':0x52,&&'s':0x53,&&'t':0x54,&&'u':0x55,&&'v':0x56,&&'w':0x57,&&'x':0x58,&&'y':0x59,&&'z':0x5A,&&'numpad_0':0x60,&&'numpad_1':0x61,&&'numpad_2':0x62,&&'numpad_3':0x63,&&'numpad_4':0x64,&&'numpad_5':0x65,&&'numpad_6':0x66,&&'numpad_7':0x67,&&'numpad_8':0x68,&&'numpad_9':0x69,&&'multiply_key':0x6A,&&'add_key':0x6B,&&'separator_key':0x6C,&&'subtract_key':0x6D,&&'decimal_key':0x6E,&&'divide_key':0x6F,&&'F1':0x70,&&'F2':0x71,&&'F3':0x72,&&'F4':0x73,&&'F5':0x74,&&'F6':0x75,&&'F7':0x76,&&'F8':0x77,&&'F9':0x78,&&'F10':0x79,&&'F11':0x7A,&&'F12':0x7B,&&'F13':0x7C,&&'F14':0x7D,&&'F15':0x7E,&&'F16':0x7F,&&'F17':0x80,&&'F18':0x81,&&'F19':0x82,&&'F20':0x83,&&'F21':0x84,&&'F22':0x85,&&'F23':0x86,&&'F24':0x87,&&'num_lock':0x90,&&'scroll_lock':0x91,&&'left_shift':0xA0,&&'right_shift ':0xA1,&&'left_control':0xA2,&&'right_control':0xA3,&&'left_menu':0xA4,&&'right_menu':0xA5,&&'browser_back':0xA6,&&'browser_forward':0xA7,&&'browser_refresh':0xA8,&&'browser_stop':0xA9,&&'browser_search':0xAA,&&'browser_favorites':0xAB,&&'browser_start_and_home':0xAC,&&'volume_mute':0xAD,&&'volume_Down':0xAE,&&'volume_up':0xAF,&&'next_track':0xB0,&&'previous_track':0xB1,&&'stop_media':0xB2,&&'play/pause_media':0xB3,&&'start_mail':0xB4,&&'select_media':0xB5,&&'start_application_1':0xB6,&&'start_application_2':0xB7,&&'attn_key':0xF6,&&'crsel_key':0xF7,&&'exsel_key':0xF8,&&'play_key':0xFA,&&'zoom_key':0xFB,&&'clear_key':0xFE,&&'+':0xBB,&&',':0xBC,&&'-':0xBD,&&'.':0xBE,&&'/':0xBF,&&'`':0xC0,&&';':0xBA,&&'[':0xDB,&&'\\':0xDC,&&']':0xDD,&&"'":0xDE,&&'`':0xC0}class POINT(Structure):&&_fields_ = [("x", c_ulong),("y", c_ulong)]def get_mouse_point():&&po = POINT()&&windll.user32.GetCursorPos(byref(po))&&return int(po.x), int(po.y)def mouse_click(x=None,y=None):&&if not x is None and not y is None:&&&&mouse_move(x,y)&&&&time.sleep(0.05)&&win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)&&win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)def mouse_dclick(x=None,y=None):&&if not x is None and not y is None:&&&&mouse_move(x,y)&&&&time.sleep(0.05)&&win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)&&win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)&&win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)&&win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)def mouse_move(x,y):&&windll.user32.SetCursorPos(x, y)def key_input(str=''):&&for c in str:&&&&win32api.keybd_event(VK_CODE[c],0,0,0)&&&&win32api.keybd_event(VK_CODE[c],0,win32con.KEYEVENTF_KEYUP,0)&&&&time.sleep(0.01)if __name__ == "__main__":&&mouse_click(1024,470)&&str = 'hello'&&key_input(str)
TA的最新馆藏你用 Python 写过哪些牛逼的程序/脚本? - Python - 伯乐在线
& 你用 Python 写过哪些牛逼的程序/脚本?
【伯乐在线导读】:有网友在 Quora 上提问,「你用 Python 写过最牛逼的程序/脚本是什么?」。本文摘编了 3 个国外程序员的多个小项目,含代码。
Manoj Memana Jayakumar, 3000+ 顶
更新:凭借这些脚本,我找到了工作!可看我在这个帖子中的回复,《》
1. 电影/电视剧 字幕一键下载器
我们经常会遇到这样的情景,就是打开字幕网站subscene 或者opensubtitles, 搜索电影或电视剧的名字,然后选择正确的抓取器,下载字幕文件,解压,剪切并粘贴到电影所在的文件夹,并且需把字幕文件重命名以匹配电影文件的名字。是不是觉得太无趣呢?对了,我之前写了一个脚本,用来下载正确的电影或电视剧字幕文件,并且存储到与电影文件所在位置。所有的操作步骤仅需一键就可以完成。懵逼了吗?
请看这个 Youtube 视频:https://youtu.be/Q5YWEqgw9X8
源代码存放在GitHub:
更新:目前,该脚本支持多个字幕文件同时下载。步骤:按住 Ctrl ,选择你想要为其下载字幕的多个文件 , 最后执行脚本即可
2. IMDb 查询/电子表格生成器
我是一个电影迷,喜欢看电影。我总是会为该看哪一部电影而困惑,因为我搜集了大量的电影。所以,我应该如何做才能消除这种困惑,选择一部今晚看的电影?没错,就是IMDb。我打开 ,输入电影的名字,看排名,阅读和评论,找出一部值得看的电影。
但是,我有太多电影了。谁会想要在搜索框输入所有的电影的名字呢? 我肯定不会这样做,尤其是我相信“如果某些东西是重复性的,那么它应该是可以自动化的”。因此,我写了一个 python 脚本, 目的是为了使用 非官方的 IMDb API 来获取数据。我选择一个电影文件(文件夹),点击右键,选择‘发送到’,然后 点击 IMDB.cmd (顺便提一下,IMDB.cmd 这个文件就是我写的 python 脚本),就是这样。
我的浏览器会打开这部电影在IMDb网站上的准确页面。
仅仅只需点击一个按键,就可以完成如上操作。如果你不能够了解这个脚本到底有多酷,以及它可以为你节省多少时间,请看这个 Youtube 视频:https://youtu.be/JANNcimQGyk
从现在开始,你再也不需要打开你的浏览器,等待加载IMDb的页面,键入电影的名字。这个脚本会帮你完成所有的操作。跟往常一样,源代码放在了GitHub: ,并且附有操作说明。当然,由于这个脚本必须去掉文件或文件夹中的无意义的字符,比如“DVDRip, YIFY, BRrip”等,所以在运行脚本的时候会有一定比例的错误。但是经过测试,这个脚本在我几乎所有的电影文件上都运行的很好。
许多人在问我是否可以写一个脚本,可以发现一个文件夹中所有电影的详细信息,因为每一次只能发现一个电影的详细信息是非常麻烦的。我已经更新了这个脚本,支持处理整个文件夹。脚本会分析这个文件夹里的所有子文件夹,从 IMDb上抓取所有电影的详细信息 ,然后打开一个电子表格,根据IMDb 上的排名,从高到低降序排列所有的电影。这个表格中包含了 (所有电影)在 IMDb URL, 年份,情节,分类,获奖信息,演员信息,以及其他的你可能在 IMBb找到的信息。下面是脚本执行后,生成的表格范例:
Your very own personal IMDb database! What more can a movie buff ask for? ;)
Source on GitHub:
你也可以有一个个人 IMDb 数据库!一个电影爱好者还能够要求更多吗?:)
源代码在 GitHub:
连载漫画下载器
我个人超级喜欢 Matthew Inman 的漫画。它们在疯狂搞笑的同时,却又发人深省。但是,我很厌烦重复点击下一个,然后才能阅读每一个漫画。另外,由于每一个漫画都由多福图片组成,所以手动下载这些漫画是非常困难的。
基于如上原因,我写了一个 python 脚本 ,用来从这个站点下载所有的漫画。这个脚本利用 BeautifulSoup ( ) 解析 HTML 数据, 所以在运行脚本前,必须安装 BeautifulSoup。 用于下载燕麦片(马修.英曼的一部漫画作品)的下载器已经上传到GitHub:
。(漫画)下载完后的文件夹是这样的 :D
成功地从 下载了整部漫画后,我在想是否我可以做同样的事情 , 从另一个我喜欢的站点— 搞笑的,唯一的 . 下载一些东西呢?
somececards 的问题是,图片命名是完全随机的,所有图片的排放没有特定的顺序,并且一共有52 个大的类别, 每一个类别都有数以千计的图片。
我知道,如果我的脚本是多线程的话,那将是非常完美的,因为有大量的数据需要解析和下载,因此我给每一个类别中的每一页都分配一个线程。这个脚本会从网站的每一个单独的分类下载搞笑的电子贺卡,并且把每一个放到单独的文件夹。现在,我拥有这个星球上最好笑的电子贺卡私人收藏。下载完成后,我的文件夹是这样的:
没错,我的私人收藏总共包括:52个类别,5036个电子贺卡。 源代码在这里:
编辑:很多人问我是否可以共享我下载的所有文件,(在这里,我要说)由于我的网络不太稳定,我没办法把我的收藏上传到网络硬盘,但是我已经上传一个种子文件,你们可以在这里下载:
种下种子,传播爱:)
Akshit Khurana,4400+ 顶
感谢 500 多个朋友在 Facebook 上为我送出的生日祝福
有三个故事让我的21岁生日变的难忘,这是最后一个故事。我倾向于在每一条祝福下亲自评论,但是使用 python 来做更好。
1. # Thanking everyone who wished me on my birthday
2. import requests
3. import json
5. # Aman's post time
6. AFTER =
7. TOKEN = '
9. def get_posts():
"""Returns dictionary of id, first names of people who posted on my wall
between start and end time"""
query = ("SELECT post_id, actor_id, message FROM stream WHERE "
"filter_key = 'others' AND source_id = me() AND "
"created_time &
LIMIT 200")
payload = {'q': query, 'access_token': TOKEN}
r = requests.get('/fql', params=payload)
result = json.loads(r.text)
return result['data']
21. def commentall(wallposts):
"""Comments thank you on all posts"""
#TODO convert to batch request later
for wallpost in wallposts:
r = requests.get('/%s' %
wallpost['actor_id'])
url = '/%s/comments' % wallpost['post_id']
user = json.loads(r.text)
message = 'Thanks %s :)' % user['first_name']
payload = {'access_token': TOKEN, 'message': message}
s = requests.post(url, data=payload)
print "Wall post %s done" % wallpost['post_id']
36. if __name__ == '__main__':
commentall(get_posts())
12345678910111213141516171819202122232425262728293031323334353637383940
…1. # Thanking everyone who wished me on my birthday2. import requests3. import json4.
5. # Aman's post time6. AFTER = 7. TOKEN = '&&'8.
9. def get_posts():10. &&&&"""Returns dictionary of id, first names of people who posted on my wall11. &&&&between start and end time"""12. &&&&query = ("SELECT post_id, actor_id, message FROM stream WHERE "13. &&&&&&&&&&&&"filter_key = 'others' AND source_id = me() AND "14. &&&&&&&&&&&&"created_time &
LIMIT 200")15.
16. &&&&payload = {'q': query, 'access_token': TOKEN}17. &&&&r = requests.get('/fql', params=payload)18. &&&&result = json.loads(r.text)19. &&&&return result['data']20.
21. def commentall(wallposts):22. &&&&"""Comments thank you on all posts"""23. &&&&#TODO convert to batch request later24. &&&&for wallpost in wallposts:25.
26. &&&&&&&&r = requests.get('/%s' %27. &&&&&&&&&&&&&&&&wallpost['actor_id'])28. &&&&&&&&url = '/%s/comments' % wallpost['post_id']29. &&&&&&&&user = json.loads(r.text)30. &&&&&&&&message = 'Thanks %s :)' % user['first_name']31. &&&&&&&&payload = {'access_token': TOKEN, 'message': message}32. &&&&&&&&s = requests.post(url, data=payload)33.
34. &&&&&&&&print "Wall post %s done" % wallpost['post_id']35.
36. if __name__ == '__main__':37. &&&&commentall(get_posts())&…
为了能够顺利运行脚本,你需要从(需适当权限)获得 token。 本脚本假设特定时间戳之后的所有帖子都是生日祝福。
尽管对评论功能做了一点改变,我仍然喜欢每一个帖子。
当我的点赞数,评论数以及评论结构在 ticker(Facebook一项功能,朋友可以看到另一个朋友在做什么,比如点赞,听歌,看电影等) 中爆涨后,我的一个朋友很快发现此事必有蹊跷。
尽管这个不是我最满意的脚本,但是它简单,快捷,有趣。
在网络实验室讨论时,有了写这个脚本的想法。 为此, 耽搁了实验室作业,深表感谢。
Tanmay Kulshrestha,3300+ 顶
好了,在我失去这个项目之前(一个猪一样的朋友格式化了我的硬盘,我的所有代码都在那个硬盘上)或者说,在我忘记这些代码之前,我决定来回答这个问题。
当我对图像处理感兴趣之后,我一直致力于研究机器学习。我写这个有趣的脚本,目的是为了分类图片,很像 Facebook 做的那样(当然这是一个不够精确的算法)。 我使用了 OpenCV 的人脸检测算法,“haarcascade_frontalface_default.xml”,它可以从一张照片中检测到人脸。
你可能已经察觉到这张照片的某些地方被错误地识别为人脸。 我试图通过修改一些参数(来修正这一问题),但还是某些地方被错误地识别为人脸,这是由相机的相对距离导致的。我会在下一阶段解决这一问题(训练步骤)。
这个训练算法需要一些训练素材,每个人需要至少需要100-120个训练素材(当然多多益善)。 我太懒了,并没有为每一个人挑选照片,并把它们复制粘帖到训练文件夹。所以,你可能已经猜到,这个脚本会打开一个图片,识别人脸,并显示每一个人脸(脚本会根据处于当前节点的训练素材给每一个人脸预测一个名字)。伴随着每次你标记的照片,Recognizer 会被更新,并且还会包含上一次的训练素材。 在训练过程中,你可以增加新的名字。我使用 python 库 tkinter 做了一个 GUI。 因此,大多数时候,你必须初始化一小部分照片(给照片中的人脸命名),其他的工作都可以交给训练算法。 因此,我训练了 Recognizer ,然后让它(Recognizer)去处理所有的图片。
我使用图片中包含的人的人名来命名图片,(例如: Tanmay&*****&*****)。 因此,我可以遍历整个文件夹,然后可以通过输入人名的方法来搜索图片。
初始状态下,当一个人脸还没有训练素材时(素材库中还没有包括这个人脸的名字),需要询问他/她的名字。
我可以增加一个名字,像这个样子:
当训练了几个素材后,它会像这个样子:
最后一个是针对应对那些垃圾随机方块而使用的变通解决方案。
带名字的最终文件夹。
所以,现在寻找图片变得相当简单。顺便提一下,很抱歉(我)放大了这些照片。
import cv2
import sys
import os,random,string
#choices=['Add a name']
current_directory=os.path.dirname(os.path.abspath(__file__))
from Tkinter import Tk
from easygui import *
import numpy as np
x= os.listdir(current_directory)
testing=[]
for i in x:
if i.find('.')==-1:
new_x+=[i]
testing+=[i]
choices=['Add a name']+x
y= range(1,len(x)+1)
def get_images_and_labels():
global current_directory,x,y,g
return (False,False)
image_paths=[]
for i in g:
path=current_directory+''+i
for filename in os.listdir(path):
final_path=path+''+filename
image_paths+=[final_path]
# images will contains face images
images = []
# labels will contains the label that is assigned to the image
labels = []
for image_path in image_paths:
# Read the image and convert to grayscale
img = cv2.imread(image_path,0)
# Convert the image format into numpy array
image = np.array(img, 'uint8')
# Get the label of the image
backslash=image_path.rindex('')
underscore=image_path.index('_',backslash)
nbr = image_path[backslash+1:underscore]
t=g.index(nbr)
# If face is detected, append the face to images and the label to labels
images.append(image)
labels.append(nbr)
#cv2.imshow("Adding faces to traning set...", image)
#cv2.waitKey(50)
# return the images list and labels list
return images, labels
# Perform the tranining
def train_recognizer():
recognizer = cv2.createLBPHFaceRecognizer()
images, labels = get_images_and_labels()
if images==False:
return False
cv2.destroyAllWindows()
recognizer.train(images, np.array(labels))
return recognizer
def get_name(image_path,recognizer):
global x,choices
#if recognizer=='':
# recognizer=train_recognizer()
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
#recognizer=train_recognizer()
x1=testing
print image_path
image = cv2.imread(image_path)
img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
predict_image = np.array(img, 'uint8')
faces = faceCascade.detectMultiScale(
scaleFactor=1.3,
minNeighbors=5,
minSize=(30, 30),
flags = http://cv2.cv.CV_HAAR_SCALE_IMAGE
for (x, y, w, h) in faces:
f= image[y:y+w,x:x+h]
cv2.imwrite('temp.jpg',f)
im='temp.jpg'
nbr_predicted, conf = recognizer.predict(predict_image[y: y + h, x: x + w])
predicted_name=g[nbr_predicted-1]
print "{} is Correctly Recognized with confidence {}".format(predicted_name, conf)
if conf&=140:
msg='Is this '+predicted_name
reply = buttonbox(msg, image=im, choices=['Yes','No'])
if reply=='Yes':
reply=predicted_name
directory=current_directory+''+reply
if not os.path.exists(directory):
os.makedirs(directory)
random_name=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
path=directory+''+random_name+'.jpg'
cv2.imwrite(path,f)
msg = "Who is this?"
reply = buttonbox(msg, image=im, choices=choices)
if reply == 'Add a name':
name=enterbox(msg='Enter the name', title='Training', strip=True)
print name
choices+=[name]
reply=name
directory=current_directory+''+reply
if not os.path.exists(directory):
os.makedirs(directory)
random_name=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
path=directory+''+random_name+'.jpg'
print path
cv2.imwrite(path,f)
# calculate window position
root = Tk()
pos = int(root.winfo_screenwidth() * 0.5), int(root.winfo_screenheight() * 0.2)
root.withdraw()
WindowPosition = "+%d+%d" % pos
# patch rootWindowPosition
rootWindowPosition = WindowPosition
def detect_faces(img):
global choices,current_directory
imagePath = img
faceCascade = cv2.CascadeClassifier(cascPath)
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
scaleFactor=1.3,
minNeighbors=5,
minSize=(30, 30),
flags = http://cv2.cv.CV_HAAR_SCALE_IMAGE
print "Found {0} faces!".format(len(faces))
for (x, y, w, h) in faces:
f= image[y-padding:y+w+padding,x-padding:x+h+padding]
cv2.imwrite('temp.jpg',f)
im='temp.jpg'
msg = "Who is this?"
reply = buttonbox(msg, image=im, choices=choices)
if reply == 'Add a name':
name=enterbox(msg='Enter the name', title='Training', strip=True)
print name
choices+=[name]
reply=name
directory=current_directory+''+reply
if not os.path.exists(directory):
os.makedirs(directory)
random_name=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
path=directory+''+random_name+'.jpg'
print path
cv2.imwrite(path,f)
def new(img,recognizer):
imagePath = current_directory+''+img
print imagePath
get_name(imagePath,recognizer)
cascPath = 'haarcascade_frontalface_default.xml'
os.system("change_name.py")
for filename in os.listdir("."):
if b%10==0 or b==1:
os.system("change_name.py")
recognizer=train_recognizer()
if filename.endswith('.jpg') or filename.endswith('.png'):
print filename
imagePath=filename
#detect_faces(imagePath)
new(imagePath,recognizer)
os.remove(filename)
raw_input('Done with this photograph')
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
…&import cv2import sysimport os,random,string#choices=['Add a name']import oscurrent_directory=os.path.dirname(os.path.abspath(__file__))from Tkinter import Tkfrom easygui import * import numpy as np
x= os.listdir(current_directory)new_x=[]testing=[]for i in x:if i.find('.')==-1:new_x+=[i]else:testing+=[i]x=new_xg=xchoices=['Add a name']+xy= range(1,len(x)+1)def get_images_and_labels():global current_directory,x,y,gif x==[]:return (False,False)image_paths=[]for i in g:path=current_directory+''+ifor filename in os.listdir(path):final_path=path+''+filenameimage_paths+=[final_path]# images will contains face imagesimages = []# labels will contains the label that is assigned to the imagelabels = []for image_path in image_paths:# Read the image and convert to grayscaleimg = cv2.imread(image_path,0)# Convert the image format into numpy arrayimage = np.array(img, 'uint8')# Get the label of the imagebackslash=image_path.rindex('')underscore=image_path.index('_',backslash)nbr = image_path[backslash+1:underscore]t=g.index(nbr)nbr=y[t]# If face is detected, append the face to images and the label to labelsimages.append(image)labels.append(nbr)#cv2.imshow("Adding faces to traning set...", image)#cv2.waitKey(50)# return the images list and labels listreturn images, labels# Perform the traniningdef train_recognizer():recognizer = cv2.createLBPHFaceRecognizer()images, labels = get_images_and_labels()if images==False:return Falsecv2.destroyAllWindows()recognizer.train(images, np.array(labels))return recognizerdef get_name(image_path,recognizer):global x,choices#if recognizer=='':# recognizer=train_recognizer()cascadePath = "haarcascade_frontalface_default.xml"faceCascade = cv2.CascadeClassifier(cascadePath)#recognizer=train_recognizer()x1=testingglobal gprint image_pathimage = cv2.imread(image_path)img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)predict_image = np.array(img, 'uint8')faces = faceCascade.detectMultiScale(img,scaleFactor=1.3,minNeighbors=5,minSize=(30, 30),flags = http://cv2.cv.CV_HAAR_SCALE_IMAGE)for (x, y, w, h) in faces:f= image[y:y+w,x:x+h]cv2.imwrite('temp.jpg',f)im='temp.jpg'nbr_predicted, conf = recognizer.predict(predict_image[y: y + h, x: x + w])predicted_name=g[nbr_predicted-1]print "{} is Correctly Recognized with confidence {}".format(predicted_name, conf)if conf>=140:continuemsg='Is this '+predicted_namereply = buttonbox(msg, image=im, choices=['Yes','No'])if reply=='Yes':reply=predicted_namedirectory=current_directory+''+replyif not os.path.exists(directory):os.makedirs(directory)random_name=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))path=directory+''+random_name+'.jpg'cv2.imwrite(path,f)else:msg = "Who is this?"reply = buttonbox(msg, image=im, choices=choices)if reply == 'Add a name':name=enterbox(msg='Enter the name', title='Training', strip=True)print namechoices+=[name]reply=namedirectory=current_directory+''+replyif not os.path.exists(directory):os.makedirs(directory)random_name=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))path=directory+''+random_name+'.jpg'print pathcv2.imwrite(path,f) # calculate window positionroot = Tk()pos = int(root.winfo_screenwidth() * 0.5), int(root.winfo_screenheight() * 0.2)root.withdraw()WindowPosition = "+%d+%d" % pos # patch rootWindowPositionrootWindowPosition = WindowPositiondef detect_faces(img):global choices,current_directoryimagePath = imgfaceCascade = cv2.CascadeClassifier(cascPath)image = cv2.imread(imagePath)gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)faces = faceCascade.detectMultiScale(gray,scaleFactor=1.3,minNeighbors=5,minSize=(30, 30),flags = http://cv2.cv.CV_HAAR_SCALE_IMAGE) print "Found {0} faces!".format(len(faces))m=0for (x, y, w, h) in faces:m+=1padding=0f= image[y-padding:y+w+padding,x-padding:x+h+padding]cv2.imwrite('temp.jpg',f)im='temp.jpg'msg = "Who is this?"reply = buttonbox(msg, image=im, choices=choices)if reply == 'Add a name':name=enterbox(msg='Enter the name', title='Training', strip=True)print namechoices+=[name]reply=namedirectory=current_directory+''+replyif not os.path.exists(directory):os.makedirs(directory)random_name=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))path=directory+''+random_name+'.jpg'print pathcv2.imwrite(path,f)def new(img,recognizer):imagePath = current_directory+''+imgprint imagePathget_name(imagePath,recognizer)cascPath = 'haarcascade_frontalface_default.xml'b=0os.system("change_name.py")for filename in os.listdir("."):b+=1if b%10==0 or b==1:os.system("change_name.py")recognizer=train_recognizer()if filename.endswith('.jpg') or filename.endswith('.png'):print filenameimagePath=filename#detect_faces(imagePath)new(imagePath,recognizer)os.remove(filename)raw_input('Done with this photograph')…
我想进一步修改它的搜索功能,其中会包含更多的搜索类型,比如基于地理位置,微笑的脸,伤心的脸等等。(这样我就可以在 Skylawns 上 搜索快乐的 Tanmay & 沮丧的 Akshay & 快乐的…)
我还写了很多脚本,但那都是很久之前的事情了,我也懒得再去检查这些代码了,我会列出部分代码。
GitHub 链接:
Gmail 邮件通知
在那段时间,我没有智能手机。 导致我常常错过来自于我所在的研究所的邮件(在我的研究所的邮件 ID),我写了一个脚本,可以在我的笔记本上运行,而且能给我的手机发信息。我使用 python 的 IMAP 库来获取邮件。我可以输入一些重要的人的名字,这样一来,当这些人给我发了邮件后,我可以收到短信通知。对于短信, 我使用了 (写了一个 python 脚本,自动登陆我的账户,然后发送 短信)。
PNR(Passenger Name Record旅客订座记录,下同) 状态短讯
铁路方面不经常发送 PNR 状态消息。因此,我写了一个脚本,可以从印度铁路网站获取 PNR 状态。这是非常容易的,因为那个网站没有验证码,即使有,也只是形同虚设的验证码(在过去,一些字母会被写在看起来像图片一样的东西上面,因为他们为这些字母使用了一个 “check” 的背景图)。 我们可以轻松地从 HTML 网页得到这些字母。我不明白他们这样做的目的是什么,难道仅仅是为了愚弄他们自己吗? 不管怎么样,我使用短信息脚本来处理它,经过一段时间间隔,它会在我的笔记本上运行一次,就像是一个定时任务,只要 PNR 状态有更新,它就会把更新信息发送给我。
YouTube 视频下载器
这个脚本会从 Youtube 页面下载所有的 Youtube 视频 以及他们所有的字幕文件(从 下载)。为了使下载速度更快一点,我使用了多线程。还有一个功能是,即使你的电脑重启了,仍然可以暂停和恢复播放下载的(视频)。我原本想做一个UI的,但是我太懒了… 一旦我的下载任务完成,我就不去关心 UI 的事情了。
板球比分通知器
我猜想这个功能已经在别的地方提到过了。一个窗口通知器。(在右下角的通知区域,它会告诉你实时比分以及评论信息)。如果你愿意的化,在某些时间段,你也可以关掉它。
WhatsApp 消息
这个并不太实用,我只是写着玩玩。因为 Whatsapp 有网页版,我使用 selenium 和 Python 下载我的所有联系人的显示图片,并且,一旦有人更新了他们的显示图片,我将会知道。(如何做到的?非常简单,在设定好时间间隔后,我会一遍又一遍的不停下载所有的头像信息,一旦照片的尺寸发生变化,我将会知道他/她更新了显示图片)。然后我会给他/她发一个信息,不错的头像。我仅仅使用了一次来测试它的可用性。
Nalanda 下载器
我们一般在这个叫 ‘Nalanda’ 的网站上下载一些教学课件以及其他的课程资料, ‘Nalanda’ 在 BITS Pilani ().
我自己懒得在考试前一天下载所有的课件,所以,我写了这个这个下载器,它可以把每一门科的课件下载到相应的文件夹。
import mechanize,os,urllib2,urllib,requests,getpass,time
start_time = time.time()
from bs4 import BeautifulSoup
br=mechanize.Browser()
br.open('https://nalanda.bits-pilani.ac.in/login/index.php')
br.select_form(nr=0)
while name=='':
print '*******'
username=raw_input('Enter Your Nalanda Username: ')
password=getpass.getpass('Password: ')
br.form['username']=username
br.form['password']=password
res=br.submit()
response=res.read()
soup=BeautifulSoup(response)
name=str(soup.find('div',attrs={'class':'logininfo'}).a.string)[:-2]
print 'Wrong Password'
f=open('details.txt','w')
f.write(username+'n'+password)
print 'Welcome, '+name
print 'All the files will be downloaded in your Drive C in a folder named "nalanda"'
#print soup.prettify()
div=soup.find_all('div',attrs={'class':'box coursebox'})
l=len(div)
for i in range(l):
s=str(d.div.h2.a.string)
s=s[:s.find('(')]
c=(s,str(d.div.h2.a['href']))
path='c:nalanda'+c[0]
if not os.path.exists(path):
os.makedirs(path)
overall=[]
for i in range(l):
response=br.open(a[i][1])
page=response.read()
soup=BeautifulSoup(page)
li=soup.find_all('li',attrs={'class':'section main clearfix'})
folder=a[i][0]
print 'Downloading '+folder+' files...'
for j in range(x):
g=li[j].ul
#raw_input('')
if g!=None:
temp=http://g.li['class'].split(' ')
#raw_input('')
if temp[1]=='resource':
#print 'yes'
#print '********************'
h=li[j].find('div',attrs={'class':'content'})
s=str(h.h3.string)
path='c:nalanda'+folder
if path[-1]==' ':
path=path[:-1]
path+=''+s
if not os.path.exists(path):
os.makedirs(path)
f=g.find_all('li')
for e in range(r):
p=f[e].div.div.a
q=f[e].find('span',attrs={'class':'resourcelinkdetails'}).contents
link=str(p['href'])
text=str(p.find('span').contents[0])
if str(q[0]).find('word')!=-1:
typ='.docx'
elif str(q[0]).find('JPEG')!=-1:
typ='.jpg'
typ='.pdf'
if typ!='.docx':
res=br.open(link)
soup=BeautifulSoup(res.read())
if typ=='.jpg':
di=soup.find('div',attrs={'class':'resourcecontent resourceimg'})
link=di.img['src']
di=soup.find('div',attrs={'class':'resourcecontent resourcepdf'})
link=di.object['data']
if not os.path.exists(path+''+text+typ):
br.retrieve(link,path+''+text+typ)[0]
print 'Connectivity Issues'
z+=[(link,text,typ)]
t+=[(s,z)]
print 'No Documents in this subject'
overall+=[o]
#raw_input('Press any button to resume')
#print overall
print 'Time Taken to Download: '+str(time.time()-start_time)+ ' seconds'
print 'Do you think you can download all files faster than this :P'
print 'Closing in 10 seconds'
time.sleep(10)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
…import mechanize,os,urllib2,urllib,requests,getpass,timestart_time = time.time()from bs4 import BeautifulSoupbr=mechanize.Browser()br.open('https://nalanda.bits-pilani.ac.in/login/index.php')br.select_form(nr=0)&&&&name=''while name=='':&&&&try:&&&&&&&&print '*******'&&&&&&&&username=raw_input('Enter Your Nalanda Username: ')&&&&&&&&password=getpass.getpass('Password: ')&&&&&&&&br.form['username']=username&&&&&&&&br.form['password']=password&&&&&&&&res=br.submit()&&&&&&&&response=res.read()&&&&&&&&soup=BeautifulSoup(response)&&&&&&&&name=str(soup.find('div',attrs={'class':'logininfo'}).a.string)[:-2]&&&&except:&&&&&&&&print 'Wrong Password'f=open('details.txt','w')f.write(username+'n'+password)f.close()print 'Welcome, '+nameprint 'All the files will be downloaded in your Drive C in a folder named "nalanda"'#print soup.prettify()div=soup.find_all('div',attrs={'class':'box coursebox'}) l=len(div)a=[]for i in range(l):&&&&d=div[i]&&&&s=str(d.div.h2.a.string)&&&&s=s[:s.find('(')]&&&&c=(s,str(d.div.h2.a['href']))&&&&path='c:nalanda'+c[0]&&&&if not os.path.exists(path):&&&&&&&&os.makedirs(path)&&&&a+=[c]#print aoverall=[]for i in range(l):&&&&response=br.open(a[i][1])&&&&page=response.read()&&&&soup=BeautifulSoup(page)&&&&li=soup.find_all('li',attrs={'class':'section main clearfix'})&&&&x=len(li)&&&&t=[]&&&&folder=a[i][0]&&&&print 'Downloading '+folder+' files...'&&&&o=[]&&&&for j in range(x):&&&&&&&&g=li[j].ul&&&&&&&&#print g&&&&&&&&#raw_input('')&&&&&&&&if g!=None:&&&&&&&&&&&&temp=http://g.li['class'].split(' ')&&&&&&&&&&&&#raw_input('')&&&&&&&&&&&&if temp[1]=='resource':&&&&&&&&&&&&&&&&#print 'yes'&&&&&&&&&&&&&&&&#print '********************'&&&&&&&&&&&&&&&&o+=[j]&&&&&&&&&&&&&&&&h=li[j].find('div',attrs={'class':'content'})&&&&&&&&&&&&&&&&s=str(h.h3.string)&&&&&&&&&&&&&&&&path='c:nalanda'+folder&&&&&&&&&&&&&&&&if path[-1]==' ':&&&&&&&&&&&&&&&&&&&&path=path[:-1]&&&&&&&&&&&&&&&&path+=''+s&&&&&&&&&&&&&&&&if not os.path.exists(path):&&&&&&&&&&&&&&&&&&&&os.makedirs(path)&&&&&&&&&&&&&&&&f=g.find_all('li')&&&&&&&&&&&&&&&&r=len(f)&&&&&&&&&&&&&&&&z=[]&&&&&&&&&&&&&&&&for e in range(r):&&&&&&&&&&&&&&&&&&&&p=f[e].div.div.a&&&&&&&&&&&&&&&&&&&&q=f[e].find('span',attrs={'class':'resourcelinkdetails'}).contents&&&&&&&&&&&&&&&&&&&&link=str(p['href'])&&&&&&&&&&&&&&&&&&&&text=str(p.find('span').contents[0])&&&&&&&&&&&&&&&&&&&&typ=''&&&&&&&&&&&&&&&&&&&&if str(q[0]).find('word')!=-1:&&&&&&&&&&&&&&&&&&&&&&&&typ='.docx'&&&&&&&&&&&&&&&&&&&&elif str(q[0]).find('JPEG')!=-1:&&&&&&&&&&&&&&&&&&&&&&&&typ='.jpg'&&&&&&&&&&&&&&&&&&&&else:&&&&&&&&&&&&&&&&&&&&&&&&typ='.pdf'&&&&&&&&&&&&&&&&&&&&if typ!='.docx':&&&&&&&&&&&&&&&&&&&&&&&&res=br.open(link)&&&&&&&&&&&&&&&&&&&&&&&&soup=BeautifulSoup(res.read())&&&&&&&&&&&&&&&&&&&&&&&&if typ=='.jpg':&&&&&&&&&&&&&&&&&&&&&&&&&&&&di=soup.find('div',attrs={'class':'resourcecontent resourceimg'})&&&&&&&&&&&&&&&&&&&&&&&&&&&&link=di.img['src']&&&&&&&&&&&&&&&&&&&&&&&&else:&&&&&&&&&&&&&&&&&&&&&&&&&&&&di=soup.find('div',attrs={'class':'resourcecontent resourcepdf'})&&&&&&&&&&&&&&&&&&&&&&&&&&&&link=di.object['data']&&&&&&&&&&&&&&&&&&&&try:&&&&&&&&&&&&&&&&&&&&&&&&if not os.path.exists(path+''+text+typ):&&&&&&&&&&&&&&&&&&&&&&&&&&&&br.retrieve(link,path+''+text+typ)[0]&&&&&&&&&&&&&&&&&&&&except:&&&&&&&&&&&&&&&&&&&&&&&&print 'Connectivity Issues'&&&&&&&&&&&&&&&&&&&&z+=[(link,text,typ)]&&&&&&&&&&&&&&&&t+=[(s,z)]&&&&if t==[]:&&&&&&&&print 'No Documents in this subject'&&&&overall+=[o]&&&&#raw_input('Press any button to resume')#print overallprint 'Time Taken to Download: '+str(time.time()-start_time)+ ' seconds'print 'Do you think you can download all files faster than this :P'print 'Closing in 10 seconds'time.sleep(10)…
我自己的 DC++
这个脚本并不是很有用,目前只有一些学生在用它, 况且,DC ++ 已经提供了一些很酷的功能。我原本可以优化我自己的版本,但是,由于我们已经有了DC ++,我并没有这么做,尽管我已经使用 nodeJS 和 python 写了一个基础版本。
工作原理:
打开 DC++ , 进入一个中心站点,然后连接,我写了一个 python 脚本来做这件事。 脚本会在 PC上创建一个服务器(可以通过修改 SimpleHTTPRequestHandler 来完成)。
在服务器端(使用了NodeJS),它会拿到 PC 的连接,共享给其他的用户。
这个是主页面:
这个页面显示了所有的用户和他们的链接。因为我给 Nick 加了一个超链接,所以在链接这一拦是空的。
所以,当用户数量增加以后,这个页面会列出所有的用户列表。基本上,这个页面充当了一个你和另外一个人联系的中间人角色。 我还做了一个在所有用户中搜索特定文件的功能。
是客户端的 python 文件(这是一段很长的代码,我上传到了 Ideone)
所有这些代码仅仅用于教育目的。
关于作者:
可能感兴趣的话题
这篇文章也同步在「Python开发者」微信公号推送了,摘一些网友的分享:
Jr :下载某网站的套图,擦边球那种…!爬了好几G图片
Eric.feng:前段时间帮产品经理和qa写了个自动在jira创建发布申请 报告bug的程序。将流程化的事情自动化,提高生产力
胡人卓:无限制刷chinanet公共热点的免费账号,并自动定时刷新
匿名用户:批量重命名,文本编码转换,爬些图片。。。貌似都是些小程序
JAMIE :初学python,写了个上班自动签到功能,嗯,还不错,可以睡懒觉了
x1ah :写了一系列网站签到脚本,挂在服务器上… 爬图片视频种子…等等等等…
八岛badao :爬某榴的图好香也不算牛逼吧,对了我自己写了爬国内2家付费教学网站视频的脚本,不过还是不放Github了
关于 Python 频道
Python频道分享 Python 开发技术、相关的行业动态。
新浪微博:
推荐微信号
(加好友请注明来意)
– 好的话题、有启发的回复、值得信赖的圈子
– 分享和发现有价值的内容与观点
– 为IT单身男女服务的征婚传播平台
– 优秀的工具资源导航
– 翻译传播优秀的外文文章
– 国内外的精选文章
– UI,网页,交互和用户体验
– 专注iOS技术分享
– 专注Android技术分享
– JavaScript, HTML5, CSS
– 专注Java技术分享
– 专注Python技术分享
& 2017 伯乐在线

我要回帖

更多关于 按键精灵输入文字脚本 的文章

 

随机推荐