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

Jor*_*ril 227 python cross-platform temporary-directory

是否有跨平台的方式获取tempPython 2.6中的目录路径?

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

nos*_*klo 339

那将是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
Run Code Online (Sandbox Code Playgroud)

为了完整起见,根据文档,它是如何搜索临时目录的:

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

  • 对我来说,OSX将它放在`/ var/folders/<garbage/here>`而不是`/ tmp`中,因为这就是`$ TMPDIR`的设置方式.见[here](http://apple.stackexchange.com/questions/3949/how-do-i-find-out-the-system-temporary-directory). (5认同)
  • 当前,在Windows 10上使用python 3.6.5,`tempfile.gettempdir()`解析为`C:\ users \ user \ AppData \ Local \ Temp`。不幸的是,这条路很长。 (2认同)

Ric*_*dle 57

这应该做你想要的:

print tempfile.gettempdir()
Run Code Online (Sandbox Code Playgroud)

在我的Windows机箱上,我得到:

c:\temp
Run Code Online (Sandbox Code Playgroud)

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

/tmp
Run Code Online (Sandbox Code Playgroud)


Acu*_*nus 11

我用:

import platform
import tempfile

tempdir = '/tmp' if platform.system() == 'Darwin' else tempfile.gettempdir()
Run Code Online (Sandbox Code Playgroud)

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

  • 至少在这种情况下,MacOS 做了正确的事情,返回给您一个用户级隔离的临时目录。我 99.99% 确定这就是您所需要的......除非您想搞乱操作系统。 (3认同)
  • @sorin 99.99% 是一个延伸。我觉得50%比较现实。我经常使用多处理,然后我可能希望所有进程使用相同的临时目录。 (3认同)
  • @Asclepius TMPDIR 是一个环境变量,据我所知,它表达了 NSTemporaryDirectory 的结果。API 文档说它是针对每个用户的,请参阅 https://developer.apple.com/documentation/foundation/1409211-nstemporarydirectory。另请参阅/sf/ask/720534391/ (2认同)

hob*_*obs 10

从@nosklo的答案中取出重要的一点并添加一个半私人沙箱目录:

import tempfile
tmp = tempfile.mkdtemp()
Run Code Online (Sandbox Code Playgroud)

这样,当您完成后(隐私,资源,安全等),您可以轻松地清理自己:

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

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

  • 你应该使用`tempfile.mkdtemp()`代替 (2认同)