在Python中获取临时目录的跨平台方法

问题:在Python中获取临时目录的跨平台方法

是否有跨平台的途径来获取 temp Python 2.6中目录?

例如,在Linux /tmp下为XP,而在XP下为C:\Documents and settings\[user]\Application settings\Temp

Is there a cross-platform way of getting the path to the temp directory in Python 2.6?

For example, under Linux that would be /tmp, while under XP C:\Documents and settings\[user]\Application settings\Temp.


回答 0

那将是tempfile模块。

它具有获取临时目录的功能,还具有一些在其中创建命名或未命名临时文件和目录的快捷方式。

例:

import tempfile

print tempfile.gettempdir() # prints the current temporary directory

f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here

为了完整起见,以下是根据文档搜索临时目录的方式:

  1. TMPDIR环境变量命名的目录。
  2. TEMP环境变量命名的目录。
  3. TMP环境变量命名的目录。
  4. 特定于平台的位置:
    • RiscOS上,由Wimp$ScrapDir环境变量。
    • 的Windows,目录C:\TEMPC:\TMP\TEMP,并\TMP按此顺序。
    • 在所有其他平台,目录/tmp/var/tmp以及/usr/tmp在这个顺序。
  5. 不得已时使用当前工作目录。

That would be the tempfile module.

It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.

Example:

import tempfile

print tempfile.gettempdir() # prints the current temporary directory

f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here

For completeness, here’s how it searches for the temporary directory, according to the documentation:

  1. The directory named by the TMPDIR environment variable.
  2. The directory named by the TEMP environment variable.
  3. The directory named by the TMP environment variable.
  4. A platform-specific location:
    • On RiscOS, the directory named by the Wimp$ScrapDir environment variable.
    • On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.
    • On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.
  5. As a last resort, the current working directory.

回答 1

这应该做您想要的:

print tempfile.gettempdir()

对于我的Windows机器,我得到:

c:\temp

在我的Linux机器上,我得到:

/tmp

This should do what you want:

print tempfile.gettempdir()

For me on my Windows box, I get:

c:\temp

and on my Linux box I get:

/tmp

回答 2

我用:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

这是因为在MacOS,即达尔文,tempfile.gettempdir()os.getenv('TMPDIR')返回一个值,如'/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; 这是我并不总是想要的。

I use:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

This is because on MacOS, i.e. Darwin, tempfile.gettempdir() and os.getenv('TMPDIR') return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; it is one that I do not always want.


回答 3

最简单的方法,基于@nosklo的注释和 答案

import tempfile
tmp = tempfile.mkdtemp()

但是,如果要手动控制目录的创建,请执行以下操作:

import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)

这样,您就可以在完成以下操作后轻松清理自己(出于隐私,资源,安全性等方面的考虑):

from shutil import rmtree
rmtree(tmp, ignore_errors=True)

这类似于Google Chrome和Linux systemd这样的应用程序。他们只是使用较短的十六进制哈希值和特定于应用的前缀来“宣传”它们的存在。

The simplest way, based on @nosklo’s comment and answer:

import tempfile
tmp = tempfile.mkdtemp()

But if you want to manually control the creation of the directories:

import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)

That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:

from shutil import rmtree
rmtree(tmp, ignore_errors=True)

This is similar to what applications like Google Chrome and Linux systemd do. They just use a shorter hex hash and an app-specific prefix to “advertise” their presence.