其实对python真是一点都不熟,在用Fabric的时候,想修改远程服务器的文件,直接用open -> write 。却发现,修改的只能是本地文件,即使用with cd() : 进入目录,再调用 open ->write,也没用。
后来用了一个比较恶心的办法,适合修改小文件:
Python代码
- def modify(filename, searched, replaced):
- tmpfile = '/tmp/remote_temp.%s.txt' % os.getpid()
- get(filename,tmpfile)
- try:
- lines = open(tmpfile, 'r').readlines()
- flen = len(lines) - 1
- for i in range(flen):
- if searched in lines[i]:
- lines[i] = lines[i].replace(searched, replaced)
- open(tmpfile, 'w').writelines(lines)
- except Exception, e:
- print e
- put(tmpfile,filename);
- os.remove(tmpfile)
代码写的烂,但能用了!这里的get/put是fabric的一些方法。即:先下载下来,修改好后再put上去!
乱七八槽 的一些函数还有这些:
Python代码
- def modify2(filename, searched, replaced):
- tmpfile = '/tmp/remote_temp.%s.txt' % os.getpid()
- get(filename,tmpfile)
- try:
- lines = open(tmpfile, 'r').readlines()
- flen = len(lines) - 1
- for i in range(flen):
- for j in range(len(searched)):
- if searched[j] in lines[i]:
- lines[i] = lines[i].replace(searched[j], replaced[j])
- open(tmpfile, 'w').writelines(lines)
- except Exception, e:
- print e
- put(tmpfile,filename);
- os.remove(tmpfile)
- def modifyReg(filename, searched, replaced):
- tmpfile = '/tmp/remote_temp.%s.txt' % os.getpid()
- get(filename,tmpfile)
- try:
- lines = open(tmpfile, 'r').readlines()
- flen = len(lines) - 1
- for i in range(flen):
- lines[i], v = re.subn(searched, replaced, lines[i])
- open(tmpfile, 'w').writelines(lines)
- except Exception, e:
- print e
- put(tmpfile,filename);
- os.remove(tmpfile)
纯记录。实在不知道怎么写好(其实也是不会写)