python 中的 Base64 字符串格式

Base64 string format in python

我在弄清楚如何将 base64 数据正确输入到 python 2.7 中的字符串格式时遇到问题。这是相关的代码片段:

fileExec = open(fileLocation, 'w+')
fileExec.write(base64.b64decode('%s')) %(encodedFile) # encodedFile is base64 data of a file grabbed earlier in the script.
fileExec.close()
os.startfile(fileLocation)

虽然看起来很傻,在这种情况下我需要使用字符串格式,因为这个脚本实际上在做什么,但是当我启动脚本时,我收到以下错误:

TypeError: Incorrect Padding

我不太确定我需要对“%s”做些什么才能让它工作。有什么建议么?我使用了错误的字符串格式吗?

更新:以下是我最终想要完成的更好的想法:

encodedFile = randomString() # generates a random string for the variable name to be written 
fileExec = randomString()
... snip ...
writtenScript += "\t%s.write(base64.b64decode(%s))\n" %(fileExec, encodedFile) # where writtenScript is the contents of the .py file that we are dynamically generating

我必须使用字符串格式,因为变量名称在我们制作的 python 文件中并不总是相同。

该错误通常意味着您的 base64 字符串可能未正确编码。但这只是代码中逻辑错误的副作用。 你所做的基本上是这样的:

a = base64.b64decode('%s')
b = fileExec.write(a)
c = b % (encodedFile)

所以您正在尝试解码文字字符串“%s”,但失败了。

它应该看起来更像这样:

fileExec.write(base64.b64decode(encodedFile))

[编辑:使用冗余字符串格式...请不要在实际代码中这样做]

fileExec.write(base64.b64decode("%s" % encodedFile))

您更新的问题表明 b64decode 部分在字符串内部,而不是在您的代码中。这是一个显着的差异。您的字符串中的代码还缺少围绕第二种格式的一组内部引号:

writtenScript += "\t%s.write(base64.b64decode('%s'))\n" % (fileExec, encodedFile)

(注意单引号...)