【发布时间】:2017-04-19 14:45:56
【问题描述】:
我有一个脚本,我需要使用 Python 3.4 在 ubuntu 和 windows 上运行,当我在 windows 上运行时出现异常,"PermissionError: [WinError 32] The process cannot access the file because it is被另一个进程使用:'C:\Users\me\Desktop\tmp9uvk57b4.txt'" 在 linux 上,它可以正常工作。
我已将我的问题归结为这个示例 sn-p。我不确定问题出在哪里,但 sn-p 需要一些文本并将其写入临时文件。过了一会儿,它会删除临时文件,这就是错误出现的地方。
#!/usr/bin/env python3
import os
import tempfile
msg = "THIS IS A HORRIBLE MESSAGE"
txt = None
try:
txt = tempfile.mkstemp(dir='.', suffix='.txt')[1]
with open(txt, "w") as f:
f.write(msg)
except Exception as exp:
raise exp
finally:
if txt:
os.remove(txt)
我认为存在一些问题,即 windows 不关闭文件而 linux 关闭文件。我可以再次明确关闭它吗?这会在Linux上搞砸什么吗?有没有好的 windows/linux gotcha 资源?
【问题讨论】:
-
您正在丢弃来自
mkstemp的文件描述符,这会使文件保持打开状态而不会删除共享。因此,您会遇到共享冲突。为什么不使用tempfile.NamedTemporaryFile?可以保证在 Windows 上将其删除,而无需手动删除它——即使进程被终止。
标签: python windows python-3.x ubuntu