如何在 Python 中的 Windows 上创建一个命名的临时文件? [英] How do I create a named temporary file on windows in Python?

查看:26
本文介绍了如何在 Python 中的 Windows 上创建一个命名的临时文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 程序,它需要创建一个命名的临时文件,该文件将在程序运行过程中打开和关闭几次,并在程序退出时删除.不幸的是,tempfile 中的所有选项似乎都不起作用:

I've got a Python program that needs to create a named temporary file which will be opened and closed a couple times over the course of the program, and should be deleted when the program exits. Unfortunately, none of the options in tempfile seem to work:

  • TemporaryFile 没有可见的名称
  • NamedTemporaryFile 创建一个类似文件的对象.我只需要一个文件名.我尝试关闭它返回的对象(在设置 delete = False 之后),但是当我稍后尝试打开文件时出现流错误.
  • SpooledTemporaryFile 没有可见的名称
  • mkstemp 返回打开的文件对象和名称;不保证程序退出时删除文件
  • mktemp 返回文件名,但不保证程序退出时删除文件
  • TemporaryFile doesn't have a visible name
  • NamedTemporaryFile creates a file-like object. I just need a filename. I've tried closing the object it returns (after setting delete = False) but I get stream errors when I try to open the file later.
  • SpooledTemporaryFile doesn't have a visible name
  • mkstemp returns both the open file object and the name; it doesn't guarantee the file is deleted when the program exits
  • mktemp returns the filename, but doesn't guarantee the file is deleted when the program exits

我尝试在上下文管理器中使用 mktemp1,如下所示:

I've tried using mktemp1 within a context manager, like so:

def get_temp_file(suffix):
    class TempFile(object):
        def __init__(self):
            self.name = tempfile.mktemp(suffix = '.test')

        def __enter__(self):
            return self

        def __exit__(self, ex_type, ex_value, ex_tb):
            if os.path.exists(self.name):
                try:
                    os.remove(self.name)
                except:
                    print sys.exc_info()

     return TempFile()

... 但这给了我一个 WindowsError(32, '该进程无法访问该文件,因为它正被另一个进程使用').该文件名由我的程序生成的进程使用,即使我确保该进程在我退出之前完成,它似乎有一个我无法控制的竞争条件.

... but that gives me a WindowsError(32, 'The process cannot access the file because it is being used by another process'). The filename is used by a process my program spawns, and even though I ensure that process finishes before I exit, it seems to have a race condition out of my control.

处理这个问题的最佳方法是什么?

What's the best way of dealing with this?

1 我这里不用担心安全问题;这是测试模块的一部分,因此不法之徒可能做的最多的事情就是导致我们的单元测试虚假失败.惊恐的事件!

1 I don't need to worry about security here; this is part of a testing module, so the most someone nefarious could do is cause our unit tests to spuriously fail. The horror!

推荐答案

我今天需要类似的东西,最后我自己写了.我正在使用 atexit.register() 注册一个函数回调,该回调在程序退出时删除文件.

I needed something similar to this today, and ended up writing my own. I'm using atexit.register() to register a function callback that removes the file when the program exits.

请注意,这里的编码标准与典型的 Python 编码标准(驼峰式而不是 using_underscores)略有不同.当然可以随意调整.

Note that the coding standards for this are slightly different from the typical Python coding standards (camelCase rather than using_underscores). Adjust at will, of course.

def temporaryFilename(prefix=None, suffix='tmp', dir=None, text=False, removeOnExit=True):
    """Returns a temporary filename that, like mkstemp(3), will be secure in
    its creation.  The file will be closed immediately after it's created, so
    you are expected to open it afterwards to do what you wish.  The file
    will be removed on exit unless you pass removeOnExit=False.  (You'd think
    that amongst the myriad of methods in the tempfile module, there'd be
    something like this, right?  Nope.)"""

    if prefix is None:
        prefix = "%s_%d_" % (os.path.basename(sys.argv[0]), os.getpid())

    (fileHandle, path) = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=dir, text=text)
    os.close(fileHandle)

    def removeFile(path):
        os.remove(path)
        logging.debug('temporaryFilename: rm -f %s' % path)

    if removeOnExit:
        atexit.register(removeFile, path)

    return path

超基础测试代码:

path = temporaryFilename(suffix='.log')
print path
writeFileObject = open(path, 'w')
print >> writeFileObject, 'yay!'
writeFileObject.close()

readFileObject = open(path, 'r')
print readFileObject.readlines()
readFileObject.close()

这篇关于如何在 Python 中的 Windows 上创建一个命名的临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆