python错误TypeError:在字符串格式化期间未转换所有参数
python错误TypeError:在字符串格式化期间未转换所有参数
研究了太久,我觉得可能错过了一些愚蠢的东西...
正在编写一个脚本将信息写入文件。所有的变量都是从另一个函数传递进来的字符串,用于写入文件。
这是我的代码:
53 def makeMainTF():
54 NameTag,mcGroupTag,mcIPTag = makeNameMCTag()
55 yourName = getAccessSecretName()
56 instanceType ="t2.micro"
57 with open ("vlslabMain.tf","w") as text_file:
58 text_file.writelines(['provider \"aws\" {\n',
59 ' ',
60 'access_key = \"${var.access_key}\"\n',
61 ' ',
62 'secret_key = \"${var.secret_key}\"\n',
63 ' ',
64 'region = \"${var.access_key}\"\n',
65 '}\n\n\n',
66 'resource \"aws_instance\" \"example\" {\n',
67 ' ',
68 'ami = \"${lookup(var.amis, var.region)}\"\n',
69 ' ',
70 'instance_type = \"%s\" \n}' % instanceType,
71 '\n\n\n\n',
72 'tags {\n',
73 ' ',
74 'Name = \"%s\"\n' % NameTag,
75 ' ',
76 'Multicast = \"%s,%s\"' % (mcGroupTag,mcIPTag),
77 ' ',
78 'Owner = \"%s\"' % yourName,
79 '\n}'])
不确定为什么会出现这个错误:
Enter Access Key: asd Enter Secret Key: asd Enter your name: asd Access Key: asd Secret Key: asd Your full name is: asd Traceback (most recent call last): File "terraTFgen.py", line 86, inmakeMainTF() File "terraTFgen.py", line 78, in makeMainTF 'Owner = \"%s\"' % yourName, TypeError: not all arguments converted during string formatting
也许我看得太久了,但我没有看到语法错误。
实际上它写出了:
Enter Access Key: asd Enter Secret Key: asd Enter your name: asd Access Key: asd Secret Key: asd Your full name is: asd
但这个错误导致脚本无法写入实际的文件。
谢谢帮助!
****编辑***
这是我用来获取yourName变量的函数:
3 def getAccessSecretName(): 4 access_key = raw_input("Enter Access Key: ") 5 secret_key = raw_input("Enter Secret Key: ") 6 yourName = raw_input("Enter your name: ") 7 print "Access Key: %s" % access_key 8 print "Secret Key: %s" % secret_key 9 print "Your full name is: %s" % yourName 10 return access_key, secret_key, yourName
在上述内容中,出现了一个Python错误:TypeError: not all arguments converted during string formatting。造成这个问题的原因是在第78行的代码中,yourName被当作一个元组(tuple)来处理。而上面的代码将yourName转换为字符串。如果只想要yourName的值被写入文件,可以使用下列方法进行修复:
1. 将函数getAccessSecretName()的第10行改为:
return access_key, secret_key, yourName
这样会返回一个包含access_key、secret_key和yourName的元组。
然后,在函数getAccessSecretName()的第55行加入以下代码:
access_key, secret_key, yourName = getAccessSecretName()
这样,三个值将被解包到不同的变量中。
最后,在第78行的代码中将以下内容替换为:
'Owner = \"%s\"' % yourName
2. 另一种方法是,如果只对yourName感兴趣,可以使用以下代码替换第55行:
yourName = getAccessSecretName()[2]
这样,将元组中指定位置的值复制给变量yourName,并忽略其他值。
以上方法都可以解决该错误。