itsource

Python에서 임시 디렉토리를 가져오는 크로스 플랫폼 방법

mycopycode 2022. 11. 26. 14:01
반응형

Python에서 임시 디렉토리를 가져오는 크로스 플랫폼 방법

Python 2.6의 디렉토리에 대한 경로를 얻을 수 있는 크로스 플랫폼 방법이 있습니까?

예를 들어 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

완전성을 위해 매뉴얼에 따라 임시 디렉토리를 검색하는 방법을 다음에 나타냅니다.

  1. 에 의해 명명된 디렉토리TMPDIR환경 변수입니다.
  2. 에 의해 명명된 디렉토리TEMP환경 변수입니다.
  3. 에 의해 명명된 디렉토리TMP환경 변수입니다.
  4. 플랫폼 고유의 장소:
    • RiscOS 에서는, 에 의해서 이름이 붙여진 디렉토리.Wimp$ScrapDir환경 변수입니다.
    • Windows 에서는, 디렉토리C:\TEMP,C:\TMP,\TEMP,그리고.\TMP,그 차례로.
    • 다른 모든 플랫폼에서는 디렉토리가/tmp,/var/tmp,그리고./usr/tmp,그 차례로.
  5. 최종 수단으로서 현재의 작업 디렉토리.

이 조작은, 다음과 같이 실행할 수 있습니다.

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'그것은 내가 항상 원하는 것은 아니다.

가장 간단한 방법은 @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)

이것은 구글 크롬이나 리눅스 같은 어플리케이션과 비슷하다.systemd16진수 해시를 짧게 하고 앱 고유의 접두사를 사용하여 자신의 존재를 "애드버타이즈"합니다.

왜 이렇게 복잡한 답이 많아?

그냥 이거 써요.

   (os.getenv("TEMP") if os.name=="nt" else "/tmp") + os.path.sep + "tempfilename.tmp"

언급URL : https://stackoverflow.com/questions/847850/cross-platform-way-of-getting-temp-directory-in-python

반응형