<p>我尝试用Python中的以下命令序列替换Word文件中的子字符串。代码本身工作得非常好——即使是使用完全相同的Word文件,但是当将其嵌入到更大规模的项目结构中时,它会在确切的位置抛出一个错误。我不知道是什么原因造成的,因为它似乎与代码无关,对我来说似乎是不可复制的。在</p>
<p>旁注:我知道是什么导致了这个错误,它是Word文件中的一个德语'u',但是它是必需的,如果代码独立运行,删除它似乎不是正确的解决方案。在</p>
<pre><code>#foo.py
from bar import make_wordm
def main(uuid):
with open('foo.docm', 'w+') as f:
f.write(make_wordm(uuid=uuid))
main('1cb02f34-b331-4616-8d20-aa1821ef0fbd')
</code></pre>
<p>在食品进口棒.py因为他做了重活。在</p>
^{pr2}$
<p>在更大范围的上下文中嵌入相同代码时,将引发以下错误:</p>
<pre><code>ERROR:root:message
Traceback (most recent call last):
File "FooBar.py", line 402, in foo_bar
bar = bar_constructor(bar_theme,bar_user,uuid)
File "FooBar.py", line 187, in bar_constructor
if(main(uuid)):
File "FooBar.py", line 158, in main
f.write(make_wordm(uuid=uuid))
File "/home/foo/FooBarGen.py", line 57, in make_wordm
search="00000000-0000-0000-0000-000000000000", replace=uuid)
File "/home/foo/FooBarGen.py", line 24, in zipinfo_contents_replace
contents = fd.read().replace(search, replace)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2722: ordinal not in range(128)
INFO:FooBar:None
</code></pre>
<p>编辑:经过进一步的检查和调试,似乎是变量'uuid'导致了这个问题。当将参数作为全文字符串('1cb02f34-b331-4616-8d20-aa1821ef0fbd')而不是使用从JSON解析的变量时,它工作得非常好。在</p>
<p>编辑2:我不得不加上<code>uuid = uuid.encode('utf-8', 'ignore')</code>,现在它工作得很好了。在</p>