我在python "icecast server“上编写了一个脚本,并在"/etc/icecast2/icecast.xml”中更改了一些字符串,如下所示:
import os,sys,re
def ices2():
changedir=open(pathh + "icecast3.xml", "w")
data=open("/etc/icecast2/icecast.xml").read()
changedir.write(re.sub("<source-password>hackme</source-password>","<source-password>123</source-password>" % x,data))
changedir.close()
ices2()
def ices1():
changedir1=open(pathh + "icecast2.xml", "w")
data=open(pathh + "icecast3.xml").read()
changedir1.write(re.sub("<relay-password>hackme</relay-password>", "<relay-password>123</relay-password>" % x,data))
changedir1.close()
os.remove(pathh + "icecast3.xml")
ices1()
def ices():
changedir2=open("/etc/icecast2/icecast.xml", "w")
data=open(pathh + "icecast2.xml").read()
changedir2.write(re.sub("<admin-password>hackme</admin-password>","<admin-password>123</admin-password>" % x,data))
changedir2.close()
os.remove(pathh + "icecast2.xml")
ices()...but它对脚本来说太长了。我怎么才能缩短它呢?我需要在一个文件中做一些更改,打开它进行更改,然后关闭它,而不会丢失任何数据。我知道它可以在一个函数中完成,但我不知道怎么做。
我需要在一个函数中进行三次更改,如下所示:
def ices():
changedir=open(pathh + "icecast3.xml", "w")
data=open("/etc/icecast2/icecast.xml").read()
changedir.write(re.sub("<source-password>hackme</source-password>","<source-password>123</source-password>",data))
changedir1.write(re.sub("<relay-password>hackme</relay-password>", "<relay-password>123</relay-password>",data))
changedir2.write(re.sub("<admin-password>hackme</admin-password>","<admin-password>123</admin-password>",data))
changedir.close()我在一个函数中做到了这一点,并且我的脚本比上面的短。但这是错的,我需要正确地做
changedir=open(pathh + "icecast3.xml", "w")
data=open("/etc/icecast2/icecast.xml").read()这里我创建了一个新文件"pathh + "icecast3.xml“(pathh-/home/user/Downloads),但我需要打开文件:
"/etc/icecast2/icecast.xml"对其执行...read操作,并将更改写入同一文件。
发布于 2012-03-13 19:07:33
这三个函数都有相同的功能,因此您可以将它们合并为一个函数。这不是一个完整的解决方案,但我认为你可以自己继续:
import os,sys,re
def ices(in_path, out_path, remove=False):
changedir = open(out_path, "w")
data = open(in_path, 'r')
changedir.write(re.sub("<source-password>hackme</source-password>","<source-password>123</source-password>" % x,data.read())) # this is wrong as well but I take it as an example
changedir.close()
data.close()
if remove:
os.remove(in_path)您可以使用以下命令调用此函数:
ices(base_path + 'icecast2.xml', base_path + 'icecast3.xml', True)提示:
与string concatenation)相比,
os.path.join来创建完整路径with statement并考虑使用它来提高可读性编辑(注意注释中的说明):
抱歉,我错过了write中的不同字符串。您可以简单地这样做:
f = open(filename, 'r')
data = f.read()
f.close()
for tag in ['source', 'relay', 'admin']
sub_str = "<{tag_name}>%s</{tag_name}>".format(tag_name=tag+'-password')
data = re.sub(sub_str % 'hackme', sub_str % '123', data)
f = open(filename+'.new', 'w')
f.write(data)
f.close()https://stackoverflow.com/questions/9682563
复制相似问题