Antkillerfarm Hacking V7.0

Python(三)

2018-12-10

Python

@classmethod和@staticmethod

class A(object):
    def foo(self, x):
        print("executing foo(%s,%s)" % (self, x))
        print('self:', self)
    @classmethod
    def class_foo(cls, x):
        print("executing class_foo(%s,%s)" % (cls, x))
        print('cls:', cls)
    @staticmethod
    def static_foo(x):
        print("executing static_foo(%s)" % x)

@classmethod类似于C++中的static,无须实例化就可以调用。@staticmethod则是普通成员函数的简写。python一般用cls表示类,而用self表示类的实例。当然,这只是编程规范的约束,而非编译器约束,使用其他名字也是可以的。

参考:

https://www.cnblogs.com/elie/p/5876210.html

python中@classmethod @staticmethod区别

class的另类用法

由于python是动态脚本语言,它的class的用法也非常灵活。你甚至无须事先定义类的成员变量,而只需要运行时添加即可。

示例:

class A():
    pass

a=A()
a.name = "Job"
a.age = 10

命令行参数

-v: 打印运行信息。

-u: stdout立即输出,无缓冲。

deep copy

https://blog.csdn.net/qq_32907349/article/details/52190796

Python的进阶:copy()与deepcopy()区别

https://mp.weixin.qq.com/s/bgk375-KxF-is5dIgV_p4g

5张图彻底理解Python中的浅拷贝与深拷贝

six

six是一个专门用来兼容Python 2和Python 3的库。它解决了诸如urllib的部分方法不兼容,str和bytes类型不兼容等“知名”问题。2x3=6?这难道就是得名的原因?

代码:

https://bitbucket.org/gutworth/six

文档:

https://bitbucket.org/gutworth/six

Python 2 to Python 3

https://www.linuxzen.com/qian-yi-dao-python-3.html

迁移到Python 3

https://www.zhihu.com/question/19698598

Python 2和Python 3有哪些主要区别?

https://mp.weixin.qq.com/s/Q3cqLuOZDSMOdAjVrCDrtQ

在Python 2.7即将停止支持时,我们为你准备了一份3.x迁移指南

https://mp.weixin.qq.com/s/J4bBvu9z3BNcwMSmmL5SMQ

Python 2大限来了!113天后自生自灭,官方不再维护更新

文件print:

Python2: print >>sys.stderr, "fatal error"
Python3: print("fatal error", file=sys.stderr)

dict切片:

Python2: 
self._layers = net.blobs.keys()
self._layers = self._layers[1:] # TypeError: 'dict_keys' object is not subscriptable

Python3:
self._layers = list(net.blobs.keys())
self._layers = self._layers[1:]

检查某对象是否为字符串或Unicode对象:

Python2: isinstance(anobj, basestring)
Python3: isinstance(anobj, str)

range & xrange

1.range会直接生成一个list对象。

2.xrange则不会直接生成一个list,而是每次调用返回其中的一个值。

所以xrange做循环的性能比range好,尤其是返回很大的时候,尽量用xrange吧,除非你是要返回一个列表。

Python 3只有range,效果和Python 2的xrange相仿,且支持slicing。

参考:

http://www.cnblogs.com/zhangjing0502/archive/2012/05/16/2503880.html

Python的range和xrange

enumerate

普通Iterator:

for item in enumerate(list):
    print(item)

带index的Iterator:

for index, item in enumerate(list):
    print(index, item)

for - else

for i in [1,2,3,4]:
    if i > 2:
        print(i)
else:
    print(i, '我是else')

三元表达式

print('y是一个负数' if y < 0 else 'y是一个非负数')

时间、日期数据的格式处理

时间数据上的格式处理,主要指strftime和strptime函数。其中前者可将时间数据转换成指定格式的字符串,而后者则将字符串转换成时间数据。

import time
a = "2013-10-10 23:40:00"
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)

日期方面也是类似的做法。

星期处理

datetime(2002, 12, 4).isoweekday() == 3

datetime(2001, 12, 31).isocalendar() == (2002, 1, 1)#(year, week number, weekday)

从上面的例子还可以看出,isocalendar可以完美的处理跨年问题。

eval

eval函数用来执行一个字符串表达式,并返回表达式的值。

示例:

eval('pow(2,2)')

粗看起来,eval函数在上面的例子中有些多此一举。然而如果字符串来自外部的话,就完全不同了。我们完全可以在任何地方嵌入python脚本。然后,只需要在用到的时候,找到并加载该字符串即可。

argparse

https://blog.csdn.net/It_way/article/details/44815141

python 命令行参数解析 argparse简单分析

pickle

pickle提供了一个简单的持久化功能。可以将对象以文件(后缀名一般为*.pkl)的形式存放在磁盘上。

参考:

https://blog.csdn.net/sinat_29552923/article/details/70833455

Python pickle模块学习

dill

dill是pickle的威力加强版。

除了提供pickle的功能之外,还可浏览对象的源代码。

示例:

dill.source.getsource(func)

Sqlite

Ubuntu下的安装方法是:

sudo apt install sqlite

Python自带了pysqlite包,用于调用sqlite。

pysqlite的helloworld程序可参见:

https://github.com/antkillerfarm/antkillerfarm_crazy/blob/master/python/pysqlite-helloworld.py

可以使用sqlite_bro软件包,查看sqlite数据库。安装方法:

sudo pip install sqlite_bro

SQLCipher是Sqlite的一个fork,添加了AES加密和其他一些安全特性。

代码:

https://github.com/sqlcipher/sqlcipher

参考:

https://mp.weixin.qq.com/s/HcmOmwWQFBIOZs8p3nr7CQ

让Python更加充分的使用Sqlite3

https://mp.weixin.qq.com/s/V2wdmpb_eAGwj6DELEn2vg

原来Python自带了数据库,用起来真方便!

zip

Python的zip函数和数据压缩的zip算法没有任何关系。

它的典型用法如下:

>>> name=['song','ping','python']
>>> age=[26,26,27]
>>> zip(name,age)
[('song', 26), ('ping', 26), ('python', 27)]
>>> for n,a in zip(name,age):
...   print n,a

zip函数属于Python的Built-in Functions,类似的函数还有:

https://docs.python.org/3.6/library/functions.html

参考:

http://www.cnblogs.com/frydsh/archive/2012/07/10/2585370.html

Python的zip函数

signal

signal包用于处理系统消息。

代码示例:

import signal

def handler(signum, frame):
    print 'Signal handler called with signal', signum
    raise IOError("Couldn't open device!")

# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)

文件名处理

(filepath,tempfilename) = os.path.split(filename)
(shotname,extension) = os.path.splitext(tempfilename)

tqdm

tqdm是一个快速,可扩展的进度条。

代码:

https://github.com/tqdm/tqdm

示例:

from tqdm import tqdm
for i in tqdm(range(9)):
    ...

其实还有一个更简单的办法:

print("\r" + "xxx", end=""):这样的话会先把console里面当前的行清除掉、再输出xxx。

参考:

https://mp.weixin.qq.com/s/1YZ7-i3X8Cb2LYEuWtd1KA

给Python代码加上酷炫进度条的几种姿势

https://mp.weixin.qq.com/s/OVb4g1KzIsxgMKjJk_hG6A

在Python中妥善使用进度条

https://mp.weixin.qq.com/s/_rCg_uFD07eZw4QLtD-fzA

Python竟然能做这样的进度条

https://mp.weixin.qq.com/s/nGOCderiyOXsHkMZwIgpoA

酷炫的Python进度条开源库:alive-progress

Captcha

Captcha是一个Python验证码库,能够生成音频和图片验证码。

CAPTCHA是Completely Automated Public Turing Test to Tell Computers and Humans Apart (全自动区分计算机和人类的图灵测试)的简称. CAPTCHA的目的是区分计算机和人类的一种程序算法,是一种区分用户是计算机和人的计算程序,这种程序必须能生成并评价人类能很容易通过但计算机却通不过的测试。

代码:

https://github.com/lepture/captcha

这个库可用于生成大量有标签的验证码,是DL入门的必备工具。

参考:

https://mp.weixin.qq.com/s/m4rNUFV4VGUBI7aWv5fgbw

中文项目:快速识别验证码,CNN也能为爬虫保驾护航

https://zhuanlan.zhihu.com/p/26078299

使用深度学习来破解captcha验证码

https://mp.weixin.qq.com/s/NsaMcgufLYO3i6eG1WO_VA

我不是机器人:谷歌最新版验证码系统ReCaptcha破解已开源

https://mp.weixin.qq.com/s/fun7k1fDrB3BYG2DK-Z7wA

如何证明你是“人”还是“机器”? 揭秘验证码技术

其他类似项目还包括:

语言 名称 网址
Java JCaptcha http://jcaptcha.sourceforge.net/
Java SimpleCaptcha http://simplecaptcha.sourceforge.net/
Java kcaptcha http://captcha.ru/en/kcaptcha/
Java patchca https://github.com/pusuo/patchca
Java SkewPassImage http://skewpassim.sourceforge.net/
Java Internet Captcha http://www.icaptcha.com/
Java Cage http://akiraly.github.io/cage/

如何通过需认证的代理获取HTTP网页

Python内置的urllib和urllib2模块都可用于获取HTTP网页,但使用范围是不同的。urllib只支持HTTP 0.9和HTTP 1.0,所以如果只是使用代理可以使用urllib.FancyURLopener类,如果该代理还需要认证的话urllib就不行了。因为代理认证是HTTP 1.1中引入的。

这时可以考虑使用urllib2模块。代码如下:

import urllib2
l_proxy_info = {
'user' : 'user',
'pass' : 'pass',
'host' : 'host',
'port' : 3128
}

l_proxy_support = urllib2.ProxyHandler({"http" : "http://%(user)s:%(pass)s@%(host)s:%(port)d" % l_proxy_info})
l_opener = urllib2.build_opener(l_proxy_support, urllib2.HTTPHandler)

urllib2.install_opener(l_opener)
usock = urllib2.urlopen('http://www.sohu.com')

Requests

上一小节大概写作于2008年,已经10年了,urllib3都出来了。

Requests是Python语言编写,基于urllib3,采用Apache2 Licensed开源协议的HTTP库。

参考:

https://mp.weixin.qq.com/s/a4mGDzKdEs7-tAPsfyL29w

Python Requests库使用指南

https://mp.weixin.qq.com/s/cyG_TpPA9eyzG70VT2m2Ww

Requests的基本用法

Celery

Celery是一个专注于实时处理和任务调度的分布式任务队列,可用于执行定时任务。

参考:

https://zhuanlan.zhihu.com/p/22304455

使用Celery

https://mp.weixin.qq.com/s/jdYiqJ98PztD7Ueu_o3Z4Q

任务队列神器:Celery入门到进阶指南

Gunicorn

Gunicorn是一个高效的Python WSGI Server,地位相当于Java中的Tomcat。

官网:

http://gunicorn.org/

参考:

http://www.cnblogs.com/ArtsCrafts/p/gunicorn.html

Gunicorn快速入门

Fork me on GitHub