Skip to content

Instantly share code, notes, and snippets.

# ubuntu install lxml requires
sudo apt-get install libxml2-dev libxslt-dev python-dev lib32z1-dev
# 在digitalocean 512M内存机器上报错,升级到1G内存正常
@ficapy
ficapy / json_ignore_err.py
Created July 13, 2015 05:23
json序列化使用default参数简单忽略错误
import json
from bson import ObjectId
a = {'1': ObjectId('53ef2d847f55f618ce13f24')}
def default(o):
"""Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
@ficapy
ficapy / get_function_args_value.py
Created July 22, 2015 10:51
返回函数参数名和传入参数值的dict表
def foo(f, b):
c = 3
# 以下写法错误,locals是会变化的即使使用list(locals())依然无法得到正确的结果
# [locals.get(i) for i in locals()]
# 以下2、3通用
frame = inspect.currentframe()
args, _, _, value = inspect.getargvalues(frame)
print({i:value.get(i) for i in args})
foo(1, 2)
@ficapy
ficapy / unicode_escape.py
Created July 27, 2015 10:01
获取文本的unicode编码拼凑字符串
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Ficapy
# Create: '15/7/27'
# from __future__ import unicode_literals
# 兼容2和3
x = '啦啦啦,'
try:
x = unicode(x, 'utf-8') if isinstance(x, str) else x
@ficapy
ficapy / func_defaylt_values.py
Created July 31, 2015 04:21
函数参数不应该使用可变变量,只是也不是完全没有作用,比如可以缓存结果啊Orz,把以前写的一个函数改写了下 直观了一些
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Ficapy
# Create: '15/7/31'
# https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects
import requests
import time
@ficapy
ficapy / check_status.py
Last active August 29, 2015 14:26
多线程请求
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Ficapy
# Create: '15/8/6'
import time
import math
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from xlrd import open_workbook
@ficapy
ficapy / regex_whole_file.py
Created August 20, 2015 08:09
不进行迭代文件使用正则匹配
import codecs
import re
import mmap
with codecs.open('a.txt', 'r+', 'utf-8') as f:
data = mmap.mmap(f.fileno(), 0)
print(re.findall(b'AccountType\=(.*)', data))
@ficapy
ficapy / adding_method.py
Created August 22, 2015 02:30
adding a method to an exists object&Monkey Path
class A(object):
pass
a = A()
# 给类添加方法
def baz(self):
print('baz')
A.baz = baz
# ==========或者
@ficapy
ficapy / test.py
Last active September 16, 2015 03:41
将装饰器改成with语句,使用with语句实现错误重试
import random
from tt import retrys
def g():
pass
class A():
def __init__(self):
@ficapy
ficapy / json_output_chinese.py
Last active September 9, 2015 02:03
JSON输出中文
# http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence
print(json.dumps({u'卧槽': u'卧槽'}, indent=4).decode('unicode-escape').encode('utf8'))
print(json.dumps({u'卧槽': u'卧槽'}, indent=4, ensure_ascii=False))