[英]Type Error when running function
I'm trying to use FileInput to replace a line in a file, if a certain word is in the line. 我正在尝试使用FileInput替换文件中的一行,如果该行中包含某个单词。 It basically appends to a file. 它基本上附加到文件。 It runs but gives me a TypeError, I'm trying to figure out where the error is. 它运行但给我TypeError,我试图找出错误在哪里。
tagname = 'somestring'
def add_tags():
for line in fileinput.FileInput('/tmp/hosttags.mk',inplace=1):
if 'end_tags' in line:
line = line.replace(""" ('end_tags',""", """('%s',
u'/%s',
[('%s', u'%s tag', [])]),
('end_tags',
u'testing/end_tags_start',
[('end_tag_id', u'end_tag_description', [])])]""") % ( tagname, tagname, tagname, tagname)
print line.strip()
error: 错误:
Traceback (most recent call last):
File "./tag_update.py", line 57, in <module>
checkmk_srv_tag_update()
File "./tag_update.py", line 54, in checkmk_srv_tag_update
add_tags()
File "./tag_update.py", line 45, in add_tags
[('end_tag_id', u'end_tag_description', [])])]""") % ( tagname, tagname, tagname, tagname)
TypeError: not all arguments converted during string formatting
end result of file being updated: 文件更新的最终结果:
('house',
u'/house',
[('house', u'house tag', [])]),
('somestring',
u'/somestring',
[('somestring', u'somestring tag', [])]),
('end_tags',
u'testing/end_tags_start',
[('end_tag_id', u'end_tag_description', [])])]
thanks 谢谢
you have wrongly put your bracket, you essentially doing 您错误地放置了括号,实际上是在做
line = line.replace("xxx", "%s %s") % (tagname, tagname)
where its suppose to be 它应该在哪里
line = line.replace("xxx", "%s %s" % (tagname, tagname) )
lets say line = 'xxx', replace text match, it will works because it 1st replace become "%s %s" % (tagname, tagname)
假设line ='xxx',替换文本匹配项,它将起作用,因为它第一次替换为"%s %s" % (tagname, tagname)
when the replace text not match, it will fail because it become original line 'xxx' % (tagname, tagname)
,thus the error 当替换文本不匹配时,它将失败,因为它变成原始行'xxx' % (tagname, tagname)
,因此错误
The error can be fix also by changing the if part into 错误也可以通过将if部分更改为
if " ('end_tags'," in line:
line = line.replace("xxx", "{0} {0}".format(tagname) )
建议使用字符串格式line = line.replace("xxx", "{0} {0}".format(tagname) )
来代替% All - thanks for your help. 全部-感谢您的帮助。 I needed to add triple quotes to get this to work on the matching string. 我需要添加三引号使它在匹配的字符串上起作用。
final code: 最终代码:
def srv_tags_update():
tags_set = []
for host,tags in ipa_hostgroups_dict.iteritems():
tags_set += tags
for host_tag in set(tags_set):
for line in fileinput.FileInput('/tmp/hosttags.mk',inplace=1):
#if 'end_tags' in line:
if """('end_tags',""" in line:
line = line.replace(""" ('end_tags',""", """('%s',
u'/%s',
[('%s', u'%s tag', [])]),
('end_tags',
""") % ( host_tag, host_tag, host_tag, host_tag )
print line.strip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.