主演这个太久了,我想我错过了一些愚蠢的事情.. 编写脚本以将信息写入文件。所有变量都是从另一个函数传入以写入文件的字符串。
这是我的代码:
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, in <module>
makeMainTF()
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
最佳答案
将第 78 行替换为以下内容并尝试 -
'Owner = \"%s\"' % " ".join(yourName),
实际上,你的名字似乎是一个元组。
上面的代码会将其转换为字符串值。
编辑:-(回答OP的最后评论)
查看 getAccessSecretName()
函数的第 10 行 -
return access_key, secret_key, yourName
它返回一个由 access_key、secret_key 和 yourName 组成的元组。
因此,如果您只想将 yourName
写入您的文件,
(选项 1)
将函数 getAccessSecretName()
中的第 55 行替换为
access_key, secret_key, yourName = getAccessSecretName()
这样您就可以将三个值解压缩到不同的变量,
并将第 78 行替换为以下内容 -
'Owner = \"%s\"' % yourName
编辑2(选项二)
如果您只对 yourName
变量感兴趣,您也可以这样做
类似的东西
yourName = getAccessSecretName()[2]
将第 55 行替换为上面的行。在这里,您将把特定位置的元组值复制到变量 yourName
并忽略其他值。
关于python错误类型错误: not all arguments converted during string formatting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928298/