在Python 2.6中,是否有一种跨平台的方法获取temp
目录的路径?
例如,在Linux下是/tmp
,而在XP下是C:\Documents and settings\[user]\Application settings\Temp
。
在Python 2.6中,是否有一种跨平台的方法获取temp
目录的路径?
例如,在Linux下是/tmp
,而在XP下是C:\Documents and settings\[user]\Application settings\Temp
。
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
TMPDIR
环境变量指定的目录。
2. 由TEMP
环境变量指定的目录。
3. 由TMP
环境变量指定的目录。
4. 平台特定的位置:
- 在RiscOS上,由Wimp$ScrapDir
环境变量指定的目录。
- 在Windows上,按照顺序为C:\TEMP
、C:\TMP
、\TEMP
和\TMP
。
- 在其他所有平台上,按照顺序为/tmp
、/var/tmp
和/usr/tmp
。
5. 作为最后的选择,使用当前工作目录。tempfile.gettempdir()
的返回值为C:\users\user\AppData\Local\Temp
,这是一个比较长的路径。 - solvingJ这个应该可以满足你的需求:
print(tempfile.gettempdir())
对于我在我的Windows电脑上,我得到:
c:\temp
而在我的Linux机器上,我得到:
/tmp
我使用:
from pathlib import Path
import platform
import tempfile
tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())
这是因为在MacOS上,即Darwin系统中,tempfile.gettempdir()
和os.getenv('TMPDIR')
返回的值通常为'/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'
,但我并不总是需要这个值。
for ((i=0;i<20;i++)) do;./testTempDir.py&;echo $!;done
。你会看到20个不同的进程ID和相同的TMPDIR。 - Stephane GaspariniTMPDIR
是每个用户独立的? - Asclepius根据 @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
所做的事情。它们只使用较短的十六进制哈希和特定于应用程序的前缀来“公开”它们的存在。
tempfile.mkdtemp()
。 - nosklomkdtemp()
版本。 - hobs (os.getenv("TEMP") if os.name=="nt" else "/tmp") + os.path.sep + "tempfilename.tmp"