1 根据函数名字符串,调用函数 getattr
参考:
方法1:用类的实例化
class A(object):
def a(self):
print 'called function a'
def b(self):
print 'called function b'
def c(self):
print 'called function c'
lst = ['a', 'b']
t = A()
for i in lst:
obj = getattr(t, i)
obj()
结果:
called function a
called function b
[Finished in 0.0s]
方法2:或者用类的静态方法
class Test():
@staticmethod
def london():
print 'visited London'
@staticmethod
def paris():
print 'visited Paris'
@staticmethod
def roma():
print 'visited Roma'
def main():
lst = ['roma', 'london']
for city in lst:
getattr(Test, city)()
if __name__ == '__main__':
main()
结果
visited Roma
visited London
[Finished in 0.0s]
方法3:用函数,但是用 sys.modules[__name__]
获得当前 py 文件。
import sys
def chips():
print 'eat chips'
def hamburger():
print 'eat hamburger'
def fried_fish():
print 'eat fried fish'
def main():
this_module = sys.modules[__name__]
lst = ['chips', 'hamburger']
for i in lst:
getattr(this_module, i)()
if __name__ == '__main__':
main()
结果:
eat chips
eat hamburger
[Finished in 0.0s]
2 requests 设定超时时间
requests 会自动重试,然而有时候并没有必要,比如内部调试接口,如果不通就是不通,不需要太长的自动重新连接。所以可以设定 requests 的超时时间 timeout=n,n是整型的秒数。
import requests
response = requests.get(url=some_url, timeout=10) # 设定10秒超时
3 用 map 与 lambda 获取列表中每个字符串的长度
lst = ['a', 'ab', 'abc', '123456', 'd']
lst_map = map(lambda x: len(x), lst)
print lst_map
print max(las_map)
# 结果
[1, 2, 3, 6, 1]
6
4 map 获取每个 list 同一个位置的数
def abc(a, b, c):
return a*100 + b*10 + c
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
s = map(abc, list1, list2, list3)
print s
# 结果
[147, 258, 369]
5 MySQL 数据导出为 CSV 格式
有时候,MySQL 数据需要供 pandas 做数据分析,需要导出为 csv 格式。
select * from proxy_list
order by id asc
limit 0,2
into outfile '/tmp/test.csv'
fields
terminated by ','
optionally enclosed by '"'
escaped by '"'
lines terminated by '\r\n';
6 查询 IP 地址的接口
http://www.ipip.net/download.html
可以用 pip 安装,但是1秒只能查 5 个地址。休息的方法如下
if count % 5 == 0:
time.sleep(1)
网友评论