티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How do I get the path and name of the file that is currently executing?

현재 실행 중인 파일의 경로와 이름을 가져오려면 어떻게 해야 합니까?

 문제 내용 

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

다른 스크립트 파일을 호출하는 스크립트가 있지만 프로세스 내에서 현재 실행 중인 파일의 파일 경로를 가져와야 합니다.

 

For example, let's say I have three files. Using execfile:

예를 들어 세 개의 파일이 있다고 가정해 보겠습니다. 실행 파일 사용:

 

  • script_1.py calls script_2.py.
  • In turn, script_2.py calls script_3.py.
script_1.py가 script_2.py를 호출합니다.
script_2.py는 script_3.py를 호출한다.

 

How can I get the file name and path of script_3.py, from code within script_3.py, without having to pass that information as arguments from script_2.py?

script_2.py에서 인수로 정보를 전달하지 않고 script_3.py 내의 코드에서 script_3.py의 파일 이름과 경로를 가져오려면 어떻게 해야 하나요?

 

(Executing os.getcwd() returns the original starting script's filepath not the current file's.)

(os.getcwd()를 실행하면 현재 파일이 아닌 원래 시작 스크립트의 파일 경로가 반환됩니다.)

 

 

 

 높은 점수를 받은 Solution 

__file__

as others have said. You may also want to use os.path.realpath to eliminate symlinks:

남들이 말하는 것처럼 os.path.realpath를 사용하여 symlink를 제거할 수도 있습니다.

 

import os

os.path.realpath(__file__)

 

 

 가장 최근 달린 Solution 

Since Python 3 is fairly mainstream, I wanted to include a pathlib answer, as I believe that it is probably now a better tool for accessing file and path information.

Python 3이 상당히 주류이기 때문에 pathlib 답변을 포함하고 싶었습니다. 이제 파일 및 경로 정보에 액세스하는 데 더 나은 도구가 될 것이라고 믿기 때문입니다.

 

from pathlib import Path

current_file: Path = Path(__file__).resolve()

 

If you are seeking the directory of the current file, it is as easy as adding .parent to the Path() statement:

현재 파일의 디렉터리를 찾는다면 Path() 문에 .parent를 추가하는 것만큼 쉽습니다.

 

current_path: Path = Path(__file__).parent.resolve()

 

 

출처 : https://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing

반응형
댓글
공지사항
최근에 올라온 글