xxdxxd
- UID
- 46114
- 帖子
- 27
- 积分
- 62
- 在线时间
- 1 小时
|
1#
xxdxxd 发表于 2008-11-07 12:32
【积累】Pyrhon 示例
[color="#ff0000"]1. split and join ref:http://blog.csdn.net/lllxy/archive/2008/08/27/2837965.aspx
$ cat split_and_join.py
#!/usr/bin/env python str = ("i am a worker, and you are a student !")
- print str
- #split the str,if not specified the separator ,the whitespace is a separator,items is a sequence items = str.split()
- print items
- #join the str sep=":"items=sep.join(items)print items
$ python2.5 split_and_join.py
i am a worker, and you are a student !
['i', 'am', 'a', 'worker,', 'and', 'you', 'are', 'a', 'student', '!']
i:am:a:worker,:and:you:are:a:student:!
[color="#ff0000"]2. import
[color="#ff0000"]$ touch a1.py
$ cat a2.py
#!/usr/bin/env python
import a1 #al是模块名称
bb = a1.b() //得到class b的一个对象bb
[color="#ff0000"]3. Backup MySQL https://dream4ever.org/showthread.php?t=76803
特点是多平台,一个脚本内可以备份多个数据库,并分别打包上传到ftp进行备份。调用了mysqldump及tar来进行数据库dump及打包。
具体参数说明参见源文件
http://5j4m.net/upload/code/mysqldbbackup.py
#!/usr/bin/python
import os
import time
import ftplib
import traceback
#config vars
systempathchr="/" #路径分割符,*nix用"/" win32用"\\"
dbuser="root" #数据库用户名
dbpwd="dbpwd" #数据库密码
dbnamelist=["dbone","dbtwo","dbthree"] #需要备份那些数据库
workdir="/path/to/backup/" #本地备份文件夹
errlogfile="databack.log" #错误日志名
ftp_addr="192.168.0.2" #ftp地址
ftp_port="2102" #ftp端口
ftp_user="databack" #ftp用户名
ftp_pwd="backpwd" #ftp密码
ftp_path="/" #存放到ftp路径
ftpqueue=[]
def ftpstor():
#login
bufsize=1024
ftp=ftplib.FTP()
try:
ftp.connect(ftp_addr,ftp_port)
ftp.login(ftp_user,ftp_pwd)
ftp.cwd(ftp_path)
for filepath in ftpqueue:
#open file for input as binary
f=open(filepath,"rb")
#store file as binary
print getfilename(filepath)
ftp.storbinary("STOR "+getfilename(filepath),f,bufsize)
f.close()
ftp.quit()
except:
path=os.path.join(workdir,errlogfile)
traceback.print_exc(file=open(path,"a"))
def dumpdb(dbname):
global ftpqueue
timeformat="%Y%m%d"
sqlvalformat="mysqldump -u%s -p\"%s\" \"%s\" >\"%s\""
tarvalformat="tar --directory=\"%s\" -zcf \"%s\" \"%s\""
nowdate=time.strftime(timeformat)
dumpfile=os.path.join(workdir,dbname+".dump")
zipfile=os.path.join(workdir,dbname+nowdate+".tar.gz")
sqlval=sqlvalformat % (dbuser,dbpwd,dbname,dumpfile)
result=os.system(sqlval)
tarval=tarvalformat % (workdir,zipfile,dbname+".dump")
result=os.system(tarval)
os.remove(dumpfile)
ftpqueue.append(zipfile)
def getfilename(path):
pt=path.rfind(systempathchr)
return path[pt+1:]
def main():
for dbname in dbnamelist:
dumpdb(dbname)
ftpstor()
main()
看到代码里面是用在得到文件名的,可以试试os.path.basename活着os.path.split了
>>> import os.path
>>> os.path.basename("c:\\test\\aa.txt")
'aa.txt'
>>> os.path.split("c:\\test\\aa.txt")
('c:\\test', 'aa.txt')
>>> os.path.split("c:\\test\\aa.txt")[-1]
'aa.txt'
>>> os.path.basename("/home/test/aa.txt")
'aa.txt'
>>> os.path.split("/home/test/aa.txt")
('/home/test', 'aa.txt')
>>> os.path.basename("/home/test/aa.txt")
'aa.txt'
|