Python协程

Python协程



import gevent, time
from urllib import request
from gevent import monkey
monkey.patch_all()

def browser(url, i):
    data = ''
    try:
        for n in range(10):
            with request.urlopen(url) as f:
                data = f.read()
            time.sleep(0.1)
            print('%d %d' % (n, i))
    finally:
        gevent.sleep(0)

tasks = []

for i in range(3000):
    tasks.append( gevent.spawn(browser, 'http://10.10.17.45/', i) )

gevent.joinall(tasks)


发布于
归类为Python

编译安装Python3

编译安装Python3


#!/bin/bash

yum install -y wget gcc make zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel

wget https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

tar zxvf Python-3.5.1.tgz
cd Python-3.5.1
./configure --prefix=/usr/local/python3
make && make install

ln -s /usr/local/python3/bin/python3 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3 /usr/bin/pip3

pip3 install --upgrade pip

发布于
归类为Python

Python解析DNS信息

Python解析DNS信息


import sys
import os
import struct
import socket
import re

host = 'www.baidu.com'
host = 'www.facebook.com'
host = 'centerqi.appspot.com'

index = os.urandom(2)
hoststr = ''.join(chr(len(x))+x for x in host.split('.'))
data = '%s\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00%s\x00\x00\x01\x00\x01' % (index, hoststr)
data = struct.pack('!H', len(data)) + data
address_family = socket.AF_INET
sock = None

dnsserver = '8.8.8.8'
sock = socket.socket(family=address_family)
sock.connect((dnsserver, 53))
sock.sendall(data)
rfile = sock.makefile('rb')
size = struct.unpack('!H', rfile.read(2))[0]
data = rfile.read(size)
ips = ['.'.join(str(ord(x)) for x in s) for s in re.findall('\xC0.\x00\x01\x00\x01.{6}(.{4})', data)]

print ips

另一种



#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket, SocketServer

def domain(data):
    data = data.split('\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00')
    if data[0] != '\x00\x01':
        name = ''
        i = 0
        for x in data[1]:
            n = ord(x)
            if n == 0:
                break
            i = i + 1
            if n < 32:
                name = name + data[1][i:i + n] + '.'
        print len(name)

def answer(data):
    # for x in data:
        # print( ord(x) )
    data = data.split('\x00\x01\x00\x01')
    print data

class DNSUDPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        socket.setdefaulttimeout(3)
        sock.sendto(self.request[0], ('223.5.5.5', 53))
        # domain(self.request[0])
        result = sock.recv(5120)
        answer(result)
        sock.close()
        self.request[1].sendto(result, self.client_address)

if __name__ == "__main__":
    server = SocketServer.UDPServer(("0.0.0.0", 53), DNSUDPHandler)
    server.serve_forever()
发布于
归类为Python

Python实现TCP Server

Python实现TCP Server


# Python 3

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):

	def handle(self):
		self.data = self.request.recv(1024)
		respone = b'HTTP/1.1 200 OK\r\n\r\nOK'
		self.request.send(respone)

if __name__ == "__main__":
	server = socketserver.ThreadingTCPServer(('0.0.0.0', 8000), MyTCPHandler)
	try:
		server.serve_forever()
	except KeyboardInterrupt:
		pass
	server.server_close()
	print('Bye')
发布于
归类为Python

Python学习笔记

Python学习笔记

一、字符串

1. 获取字符串的数字编码


ord('字符串')

2. 整数编码转换为字符串


chr(66)

3. 字符串转换为字节码 bytes


"字符串".encode('utf-8')

4. 字节码转换为字符串


b"abc".decode('utf-8')

5. 获取字符串长度


len('str中文')

6. 字符串格式化


"My name is %s, code is %d" % ('json', 100)

7. 截取字符串(切片)


str[0:3]

二、列表和元组

1. 初始化一个列表


classmates = []

2. 计算列表元素个数


len(classmates)

3. 添加元素


classmates.append('Adam')

4. 插入元素


classmates.insert(1, 'Jack')

5. 删除末尾的元素


classmates.pop()

6. 元组(不可变的列表)


classmates = ('Michael', 'Bob', 'Tracy')

7. 遍历列表


names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

8. 取一部分(切片)


classmates[0:3]

三、字典(dist)

1. 创建


d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}

2. 判断 key 是否存在


 'Bob' in d

3. 获取某个元素


d['Bob']
d.get('Thomas') 

4. 删除一个元素


d.pop('Bob')

四、 集合

1. 创建集合


s = set([1, 2, 3])

2. 添加元素


add(4)

3. 删除元素


remove(4)

4. 取交集


s1 & s2

5. 取并集


s1 | s2

五、高级特性

发布于
归类为Python