with open("filename") as f: for line in f.readlines(): # do sth with line
删除 setup.py 安装的 Python 软件包
2011年4月3日
在 CentOS 5.5 上通过 setup.py 安装了一个软件包。删除的时候发现 setup.py 没有 uninstall 选项。
在网上找了个简单的方法,2 个步骤可轻松完成卸载:
* 增加 –record 参数重新安装软件包,执行命令:
# python ./setup.py install --record install.txt
* 删除安装文件,执行命令:
# cat install.txt | xargs rm -rf
sudo python ./setup.py install
sudo python ./setup.py install --record install.txt ; cat install.txt | xargs rm -rf
命令行下查看python和numpy的版本和安装位置
1、查看python版本
方法一:
python -V
注意:‘-V‘中‘V’为大写字母,只有一个‘-’
方法二:
python --version
注意:‘--version'中有两个‘-’
2、查看python安装位置
方法一:
python -c "import sys; print sys.executable"
方法二:
python -c "import os; print os.sys.executable"
python -c "import os; path = os.sys.executable;folder=path[0 : path.rfind(os.sep)]; print folder"
3、查看Numpy版本
python -c "import numpy; print numpy.version.version"
或
python -c "import numpy; print numpy.__version__"
4、查看Numpy安装路径
python -c "import numpy; print numpy.__file__"
python中
a=0
if a: #这个条件为假
xxx
用filter过滤 list 中的某些值
a = [1,1,1,2,3]
如果想把1去掉:
a = filter(lambda x: x != 1, a)
遍历字典dict
a = {1:’a’,2:’b’}
[(k,v) for (k,v) in a.items()]
int最大值
import sys
sys.maxint
解析URL参数
import urlparse
url = 'http://www.x.com/login.html?password=123456&usrname=pan'
rs = urlparse.urlparse(url)
q = urlparse.parse_qs(rs.query)
print q
查找字符串
a = ‘asdf’
a.find(‘sd’),返回1,字符串从0开始编码
如果没有找到,返回-1
正则表达式
m = re.search("(book)+","mebookbookme")
m.group()
http://www.cnblogs.com/wei-li/archive/2012/05/16/2505503.html
字典按照key或者value排序
cc_diff = sorted(cc_diff.items(), key=lambda (k, v): v, reverse=True)
最后cc_diff是一个(k,v)的list
unicode和utf-8编码
在CentOs上的系统环境是utf-8,但是从互联网上抓取下来的html文本是unicode编码,所以在使用之前全部通过u’some message’.encode(‘utf8)
默认情况下 ‘123’ + u’abc’会报错
一般情况下都是在同一种编码,比如utf-8下进行字符串之前的+操作,如果需要在+操作的时候自动将utf-8转换成unicode的话,可以使用
import sys
reload(sys)
sys.setdefaultencoding('utf8')
python的”main”函数
#hello.py
def foo():
str="function"
print(str);
if __name__=="__main__":
print("main")
foo()
查询类的所有属性
class foo():
a=1
print vars(foo)
数组分片
a = [1,2,3,4]
注意 “:” 是位置的分隔符,x:y代表[x,y)这一段元素,二在numpy中,:代表的是所有的行或者列
a[:]全部元素
a[:3]前3个元素
a[1:3] 第1、2两个元素,所以从0开始
子模块引用上级模块
如果直接运行子模块,需要向sys.path中添加子模块父目录
from os import listdir
from os.path import abspath, isfile, isdir, join, dirname
import sys
file_parts = dirname(abspath(__file__)).split('/')
parent_path = '/'.join(file_parts[:len(file_parts)-1])
print parent_path
sys.path.append(parent_path)
当前模块绝对路径
import os
print os.path.abspath(__file__) // 文件绝对路径
print os.path.dirname(os.path.abspath(__file__)) //文件所在目录
文件或者目录是否存在
if os.path.exists(‘/usr/local/bin’)
创建目录
os.mkdir(‘xiachufang/machine_group’)’
命令行参数
import sys
print '参数个数为:', len(sys.argv), '个参数。'
print '参数列表:', str(sys.argv)
测试:
$ python test.py arg1 arg2 arg3
参数个数为: 4 个参数。
参数列表: ['test.py', 'arg1', 'arg2', 'arg3']
去掉空白符
a = ‘1 2 3 (tab) 4 ‘
a = re.sub(‘\s+’, ‘’, a)
找到list中指定元素的下表
a = [11, 22, 33]
a.index(22)返回1
class的成员和对象的成员
test.py中有如下代码:
class Kls(object):
no_init = 0
def __init__(self):
self.no_init = self.no_init + 100
Kls.no_init += 1
print self.no_init
print Kls.no_init
if __name__ == "__main__":
init1 = Kls()
init2 = Kls()
运行python test.py输出为:
100
1
101
2
值得说明的是,在class中声明的属性,对象实例第一次引用的时候是取的类的属性,一旦对象的属性进行了操作,比如init1.no_init += 123,则no_init属性就会脱离类而附着于对象之上。对象是无法改变类的属性值的。对于这个例子,Kls.no_init两次分别累加1,而对于init1,在初始化的时候使用了类的属性值Kls.init=0,所以累加100之后init1.no_init=100,之后类的属性值+1,Kls.no_init=1;然后init2初始化的时候,第一次引用了类的属性值Kls.no_init=1,再累加100,最后init2.no_init=101,后面类的属性值+1,则Kls.no_init = 2
@classmethod和@staticmethod装饰器
@classmethod修饰的方法,无论是类访问还是实例访问,修改的属性都是类属性,默认转入类
@staticmethod修饰的方法,和类已经没有关系了,默认不传入任何参数,操作的是一些固有存在的变量,比如环境变量
例子,test.py中
class Kls1:
no_init = 0
def __init__(self):
Kls1.no_init += 1
def printd(self):
print self.no_init
@classmethod
def cmethod(*args):
print args
@staticmethod
def smethod(*args):
print args
if __name__ == "__main__":
init1 = Kls1()
init2 = Kls1()
init1.cmethod(123123)
init1.smethod(123123)
init1.printd()
print '-------------------'
Kls1.cmethod()
Kls1.smethod()
Kls1.printd()
运行python test.py得到:
(<class __main__.Kls1 at 0x1029a60b8>, 123123)
(123123,)
2
-------------------
(<class __main__.Kls1 at 0x1029a60b8>,)
()
Traceback (most recent call last):
File "test.py", line 74, in <module>
Kls1.printd()
TypeError: unbound method printd() must be called with Kls1 instance as first argument (got nothing instead)
stdout立即刷新,尤其是在重定向的时候
sys.stdout.flush()
unicode转utf8
u’123’.encode(‘utf8)
utf8转unicode
‘123’.deocde(‘utf8’)
计算MD5
import md5
def GetStringMD5(str):
m = md5.new()
m.update(str)
return m.hexdigest()
Python的模块引用和查找路径http://www.cnblogs.com/qingspace/p/5284480.html
import sys
print sys.path
获取当前时间戳
import time
from datetime import datetime, timedelta, date
created = datetime.now()
created = int(time.mktime(created.timetuple()))
使用map
a=[‘1’,’2’]
map(int, a)
返回[1,2]
map(func, a)会将a中的每个元素都用func来作用一下,最后的结果放到一个list中
python中对象的拷贝和引用
参考:https://my.oschina.net/leejun2005/blog/145911
不可变对象包括int,float,long,str,tuple等
可变对象包括list,set,dict等
需要注意的是:这里说的不可变指的是值的不可变
对于不可变对象的赋值,比如a=’123’,然后让a = ‘qwe’,那么会重新生成一个字符串对象,并把a这个标签从’123’上撕下来贴到’qwe’上
对于可变对象a = [1,2,3], b = [] 然后 a = b 只是把a贴到[]上而已
浅拷贝和深拷贝
a = [1,2,3]
a[1] = a
print a
输出[1, [...], 3]
这是因为
而
a = [1,[11,22,33],3]
b = a[:] # 浅拷贝
a[0] = 9
b[1][1] = 777
print a, b
结果
a = [9,[11,777,33],3]
b = [1,[11,777,33],3]
原理
import copy
a = [0, [1, 2], 3]
b = copy.deepcopy(a)
a[0] = 8
a[1][1] = 9
结果
>>> a
[8, [1, 9], 3]
>>> b
[0, [1, 2], 3]
引用 VS 拷贝:
(1)没有限制条件的分片表达式(L[:])能够复制序列,但此法只能浅层复制。
(2)字典 copy 方法,D.copy() 能够复制字典,但此法只能浅层复制
(3)有些内置函数,例如 list,能够生成拷贝 list(L)
(4)copy 标准库模块能够生成完整拷贝:deepcopy 本质上是递归 copy
(5)对于不可变对象和可变对象来说,浅复制都是复制的引用,只是因为复制不变对象和复制不变对象的引用是等效的(因为对象不可变,当改变时会新建对象重新赋值)。所以看起来浅复制只复制不可变对象(整数,实数,字符串等),对于可变对象,浅复制其实是创建了一个对于该对象的引用,也就是说只是给同一个对象贴上了另一个标签而已。
urllib下载图片
def download_image(url):
# print 'task begin', url
r = requests.Session()
r.keep_alive = False
try:
image = r.get(url, stream=True, verify=False)#, timeout=10)
except Exception as e:
print e
print url
return None
# print 'done'
if image.status_code == 200:
return image.content
return None
计算程序运行时间
import time
start = time.time()
... do something
elapsed = (time.time() - start)
获取当前进程pid
os.getpid()
获取当前时间
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
import time
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
yield 使用
参考:https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/
用 pip 在指定路径下安装软件
pip install -t /usr/local/Python-2.7.13/lib/python2.7/site-packages tornado
查看django版本
import django
django. VERSION
查看python中Unicode字符串的编码
s = "高德路"
# 把字符串s编码成unicode
st = s.encode('unicode_escape')
>>> print(st)
b'\\u9ad8\\u5fb7\\u8def'
2018年3月28日18:13:49 —— 执行Python命令的时候,将文件的编码(比如utf-8)转换到python内部编码(比如Unicode)时,使用的“我(python)认为文件应该是这样的编码”是本地编码,用如下命令得到:
import locale
locale.getpreferredencoding()
判断文件夹或文件是否存在
import os os.path.isfile('test.txt') #如果不存在就返回False os.path.exists(directory) #如果目录不存在就返回False
进入文件夹并执行shell 命令
import os class cd: """Context manager for changing the current working directory""" def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(self.savedPath) import subprocess # just to call an arbitrary command e.g. 'ls' # enter the directory like this: with cd("~/Library"): # we are in ~/Library subprocess.call("ls")
遍历文件夹
# -*- coding: utf-8 -*- import os def Test1(rootDir): list_dirs = os.walk(rootDir) for root, dirs, files in list_dirs: for d in dirs: print os.path.join(root, d) for f in files: print os.path.join(root, f)
获取当前工作目录
import os
os.getcwd() #获取当前工作目录
向list中添加元素
list = [] list.append(11)
extend() 将一个列表中每个元素分别添加到另一个列表中,
>>> a = [1,2,3] >>> a.extend(a) >>> a [1, 2, 3, 1, 2, 3]
>>> a =[1,2,3]
>>> a+a
[1, 2, 3, 1, 2, 3]
去掉两端引号
a='"srting"' print(a) b=eval(a) print(b)
集合操作
>>> x = set('spam') >>> y = set(['h','a','m']) >>> x, y (set(['a', 'p', 's', 'm']), set(['a', 'h', 'm'])) 再来些小应用。 >>> x & y # 交集 set(['a', 'm']) >>> x | y # 并集 set(['a', 'p', 's', 'h', 'm']) >>> x - y # 差集 set(['p', 's']) 添加数据 x.add('aaa')
判断元素是否在集合中
'aaa' in x
读取/写入文件
with open("yourfile") as f: for line in f.readlines(): # do sth with line
f = open("yourfile", "w")
f.write("something")
f.close()
删除一行文本首位空格
a = ' 111 ' a = a.strip()
判断元素在 set中的效率要远远高于list
for i in xrange(0, 5000000): if i in listA: pass for i in xrange(0, 5000000): if i in setA: pass 第一个循环用了16min,第二个循环用了52s。
字符串截取
>>> a = "123" >>> a[0:2] '12'
判断字典是否含有某个key
#生成一个字典 d = {'name':Tom, 'age':10, 'Tel':110} #打印返回值 print d.has_key('name') #结果返回True
#生成一个字典 d = {'name':Tom, 'age':10, 'Tel':110} #打印返回值,其中d.keys()是列出字典所有的key print ‘name’ in d.keys() print 'name' in d #两个的结果都是返回True
除了使用in还可以使用not in,判定这个key不存在,使用in要比has_key要快
sleep
import time time.sleep(1) # 休眠1秒
将 list 数据添加到set 中
>>> a = [1,2,3] >>> a [1, 2, 3] >>> b = b.union(set(a)) >>> b set([1, 2, 3])
dict update 操作
>>> a = {'aaa':1,'bbb':2} >>> a {'aaa': 1, 'bbb': 2} >>> a.update({'abase_ids':[1,2,3], 'hbase':[]}) >>> a {'abase_ids': [1, 2, 3], 'hbase': [], 'aaa': 1, 'bbb': 2}
字符串转小写
>>> 'SDFSFSF'.lower() 'sdfsfsf'
将一个list批量加入另一个list
>>> a = [1,2,3] >>> b = [11,22] >>> a+b [1, 2, 3, 11, 22]
生成随机数
import random
random.randint(0,9)
子类调用父类方法
class BaseTask(luigi.Task): hdfs_client = create_hadoopcli_client() #hdfs_client = HdfsClient.get_hdfs_client() day = luigi.Parameter(default="20170922") # run day define_metrics() st = time.time() @property def task_name(self): raise NotImplemented @property def flag(self): return self.day @property def name(self): return '{}_{}_{}'.format(self.task_name, self.day, JOB_USER) # task flag hdfs file when success def output(self): path = "{target_root}/{task_name}/day={day}/_SUCCESS".format( target_root=FLAG_ROOT, task_name=self.task_name, day=self.flag) return luigi.hdfs.HdfsTarget(path, format=luigi.hdfs.PlainFormat) # set status flag when success def on_success(self): println('xxxxx') class TestBaseTask(BaseTask): @property def task_name(self): return 'test_base_task_flag_file' @property def flag(self): return '11111111' def run(self): super(TestBaseTask, self).on_success() print 'ooooooooookkkkkkkkkk' if __name__ == '__main__': test = TestBaseTask() test.run()
字符串替换
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。 str = "this is string example....wow!!! this is really string"; print str.replace("is", "was"); print str.replace("is", "was", 3); thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string
时间戳转换为时间
# 时间戳转时间 # tl = time.localtime() tl = 1489660028.0 format_time = time.strftime("%Y-%m-%d %H:%M:%S", tl) // 2017-03-16 18:22:06 ts = time.strptime(format_time, "%Y-%m-%d %H:%M:%S") # 格式化时间转时间戳 time.mktime(ts) // 1489660028.0 --------------------- 作者:holdlg 来源:CSDN 原文:https://blog.csdn.net/holdlg/article/details/62436537 版权声明:本文为博主原创文章,转载请附上博文链接!
super() raises “TypeError: must be type, not classobj” for new-style class
是因为python 2.7的基类没有继承object
class BaseOne(object): ut = 0 uid = 0 def __init__(self, ut=0, uid=0): self.ut = ut self.uid = uid def hi(self): print "hi from base" class ChildOne(BaseOne): start_time =111 end_time =222 def hi(self): print "hi from ChildOne" super(ChildOne, self).hi() class ChildTwo(BaseOne): def __init__(self): pass co = ChildOne(123,321)
循环迭代 字段
for key, value in d.iteritems(): print key, value
创建文件
open('xxx', 'w').close()