programing

__file__ 변수는 무슨 뜻입니까?

nicegoodjob 2023. 1. 16. 20:13
반응형

__file__ 변수는 무슨 뜻입니까?

import os

A = os.path.join(os.path.dirname(__file__), '..')

B = os.path.dirname(os.path.realpath(__file__))

C = os.path.abspath(os.path.dirname(__file__))

난 보통 이걸 실제 경로와 연결시켜. 실행가 있기 에 꼭 . 그리고 저는 이 문장에 대해 정말 이해하고 싶습니다.os.path사용할 수 있도록 모듈을 설정합니다.

Python, Python의 에서 __file__패스로 설정됩니다.그런 다음 이 기능을 다른 함수와 함께 사용하여 파일이 있는 디렉터리를 찾을 수 있습니다.

한 번에 하나씩 예를 들어 보겠습니다.

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

여기서 반환되는 다양한 값을 확인할 수 있습니다.

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

에서 실행해 를 들어, 다음과 같습니다)../text.py,~/python/text.py등)이 어떤 차이가 있는지 확인합니다.

먼저 몇 가지 혼란을 해결하고 싶습니다. __file__와일드카드가 아니라 속성입니다.이중 밑줄 속성 및 방법은 관례상 "특별한" 것으로 간주되며 특별한 목적을 위해 사용됩니다.

http://docs.python.org/reference/datamodel.html 에는 특별한 메서드나 Atribute의 대부분이 표시됩니다(전부는 아니더라도).

경우, 「 」__file__는 모듈(모듈 오브젝트)의 어트리뷰트입니다. a Python a 서서 in in .py줄서다 ★★★★★★★★★★★★★★★★★.import amodule will 、 will will will will will will will will will will 。__file__츠키노

문서에서 가져온 내용:

__file__는 모듈이 파일에서 로드된 경우 모듈이 로드된 파일의 경로 이름입니다.__file__Atribute는 인터프리터에 스태틱하게 링크되어 있다C 모듈에는 존재하지 않습니다.공유 라이브러리에서 동적으로 로드된 확장 모듈의 경우 공유 라이브러리 파일의 경로 이름입니다.

자체 입니다.__file__아트리뷰트

이것을 실제로 확인하려면 , 다음의 조작을 실시합니다.

# file: test.py

print globals()
print __file__

실행:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

설명서에 따르면:

__file__는 모듈이 파일에서 로드된 경우 모듈이 로드된 파일의 경로 이름입니다.__file__Atribute는 인터프리터에 스태틱하게 링크되어 있다C 모듈에는 존재하지 않습니다.공유 라이브러리에서 동적으로 로드된 확장 모듈의 경우 공유 라이브러리 파일의 경로 이름입니다.

, 다음과 같은 것도 있습니다.

__file__되어 있지 한 "경로"가 "에 ).sys.builtin_module_names아트리뷰트

일부 사용자를 혼란스럽게 할 수 있는 변경에 대한 간단한 메모(대부분 질문의 설명보다는 질문의 제목에 대한 답변)를 여기에 추가합니다.3.4에서는 Python 3.4 기 、 Python 3.4 the 、 Python 3.4 the the the the the the the the the the the the the the the the the the the the the the the the the the the the 에 약간의 변화가 .__file__동작:

  • 모듈이 직접 실행되는 경우 사용되는 모듈의 상대 경로로 설정됩니다.
  • 그렇지 않으면 파일의 절대 경로로 설정됩니다.

모듈__file__Atribute(및 관련 값)에는 디폴트로 항상 절대 경로가 포함되어 있어야 합니다.단,__main__.__file__(제18416호에 Brett Cannon에 의해 기고됨)

:

모듈 x를 직접 호출하고 모듈y를 간접 호출한다.

# x.py:
from pathlib import Path
import y
print(__file__)
print(Path(__file__))
print(Path(__file__).resolve())

# y.py:
from pathlib import Path
print(__file__)
print(Path(__file__))

입니다.python3 x.py출력:

/home/aderchox/mytest/y.py                                                                                                                       
/home/aderchox/mytest/y.py                                                                                                                       
x.py                                                                                                                                             
x.py                                                                                                                                             
/home/aderchox/mytest/x.py

사용.__file__여러 가지와 조합하여os.pathmodules 에서는 모든 경로가 현재 모듈의 디렉토리 위치에 상대적입니다.이를 통해 모듈/프로젝트를 다른 기계로 이동할 수 있습니다.

프로젝트에서는 다음을 수행합니다.

A = '/Users/myname/Projects/mydevproject/somefile.txt'

그런 다음 다음과 같은 배포 디렉토리를 사용하여 서버에 배포하려고 합니다./home/web/mydevproject/코드가 경로를 올바르게 찾을 수 없게 됩니다.

언급URL : https://stackoverflow.com/questions/9271464/what-does-the-file-variable-mean-do

반응형