Windows Python 跨进程文件访问

OS: windows 7 python: 2.7

最近在把Android OTA的整套东西移植到windows上,涉及了很多python脚本,要疯了。暂不说没写过一行python了,就是windows系统也有很多年头没动过了,这个牛X的系统,居然还是那么难用。

问题描述:

temp_zip_file = tempfile.NamedTemporaryFile()

#同一线程访问temp_zip_file

#不同线程访问temp_zip_file

temp_zip_file.close()

运行时提示错误:

另一个程序正在使用此文件,进程无法访问。

靠啊,这么简单的一条语句还能出啥问题啊,在Linux上也是没有问题的,查查文档,发现下面这句话:

tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])

This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the file object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If delete is true (the default), the file is deleted as soon as it is closed.
The returned object is always a file-like object whose file attribute is the underlying true file object. This file-like object can be used in a with statement, just like a normal file.

一股浓烈的鄙视之情不由自主的直往上冒。。。。。。。

解决方法:

NamedTemporaryFile默认情况下在被调用close()后会自动删除掉(跟linux的unlink差不多),加上delete=False后可以改变这个行为,但是最后要记得手工去删除这个临时文件。最后代码就变成了这个样子:

temp_zip_file = tempfile.NamedTemporaryFile(delete = False)

#同一线程访问temp_zip_file后需要关闭该文件
temp_zip_file.close()

#不同线程访问temp_zip_file
temp_zip_file = open(temp_zip_file.name, 'rb')

#最后删除文件
os.remove(temp_zip_file.name)

ref: http://bugs.python.org/issue14243#msg164504 ref: https://docs.python.org/2/library/tempfile.html ref: http://stackoverflow.com/questions/15169101/how-to-create-a-temporary-file-that-can-be-read-by-a-subprocess/15235559#15235559