Python에서 실행 파일 경로 결정
소개
현재 실행 중인 Python 스크립트의 경로를 식별하는 것은 다양한 애플리케이션에서 중요한 측면입니다. 그러나 다양한 시나리오에 걸쳐 작동하는 "범용" 접근 방식을 찾는 것은 어려울 수 있습니다. 이 문서에서는 여러 가지 방법을 살펴보고 이와 관련된 제한 사항을 해결하여 궁극적으로 포괄적인 솔루션을 제시합니다.
기존 방법의 한계
- path = os.path.abspath(os. path.dirname(sys.argv[0])): execfile과 같은 메서드를 통해 다른 디렉터리에 있는 다른 스크립트에서 스크립트를 실행할 때 이 접근 방식은 실패합니다.
-
path = os.path.abspath(os.path.dirname(__file__)): 이 방법은 다음과 같은 경우에는 작동하지 않을 수 있습니다:
- file 속성이 존재하지 않는 경우(예: , Py2exe 실행)
- execute()를 사용하여 IDLE에서 코드가 실행됩니다.
- file이 정의되지 않았습니다(예: Mac OS X v10.6)
종합 솔루션
실행 컨텍스트에 관계없이 현재 실행 중인 파일의 경로를 얻으려면 검사 및 os 모듈의 기능 조합을 사용할 수 있습니다.
from inspect import getsourcefile from os.path import abspath path = abspath(getsourcefile(lambda:0))
이 솔루션은 다음을 포함한 다양한 시나리오에서 소스 파일 경로를 검색하는 일관된 접근 방식을 제공합니다.
- 메인 스크립트 직접 실행
- 다른 스크립트에서 실행
- 함수 내 실행
- 인터프리터 내 실행(예: IDLE)
예제 테스트
다음 디렉터리 구조를 고려하세요.
C:. | a.py \---subdir b.py
그리고 a.py 내의 코드:
#! /usr/bin/env python import os, sys print "a.py: os.getcwd()=", os.getcwd() print execfile("subdir/b.py")
subdir/b.py 내의 코드:
#! /usr/bin/env python import os, sys print "b.py: os.getcwd()=", os.getcwd() print
python a.py의 출력은 다음과 같습니다. :
a.py: os.getcwd()= C:\ b.py: os.getcwd()= C:\zzz
이는 os.getcwd()가 실행되는 스크립트의 위치와 다를 수 있는 실행 컨텍스트의 작업 디렉터리를 반영함을 보여줍니다. 이와 대조적으로 제안된 솔루션(abspath(getsourcefile(lambda:0)))은 실행 컨텍스트에 관계없이 스크립트의 소스 파일 경로를 일관되게 생성합니다.
위 내용은 Python에서 실행 파일의 경로를 어떻게 안정적으로 결정할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PythonlistsCanstoreAnyDatAtype, ArrayModuLearRaysStoreOneType 및 NUMPYARRAYSAREFORNUMERICALPUTATION.1) LISTSAREVERSATILEBUTLESSMEMORY-EFFICENT.2) ARRAYMODUERRAYRAYRAYSARRYSARESARESARESARESARESARESAREDOREDORY-UNFICEDONOUNEOUSDATA.3) NumpyArraysUraysOrcepperperperperperperperperperperperperperperperferperferperferferpercient

whenyouattempttoreavalueofthewrongdatatypeinapythonaphonarray, thisiSdueTotheArrayModule의 stricttyPeenforcement, theAllElementStobeofthesAmetypecified bythetypecode.forperformancersassion, arraysaremoreficats the thraysaremoreficats thetheperfication the thraysaremorefications는

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

thescriptIsrunningwithHongpyThonversionDueCorRectDefaultTerpretersEttings.tofixThis : 1) checktheDefaultPyThonVersionUsingPyThon-VersionorPyThon3- version.2) usvirtual-ErondmentsBythePython.9-Mvenvmyenv, 활성화, 및 파괴

PythonArraysSupportVariousOperations : 1) SlicingExtractsSubsets, 2) 추가/확장 어드먼트, 3) 삽입 값 삽입 ATSpecificPositions, 4) retingdeletesElements, 5) 분류/ReversingChangesOrder 및 6) ListsompectionScreateNewListSbasedOnsistin

NumpyArraysareSentialplosplicationSefficationSefficientNumericalcomputationsanddatamanipulation. Theyarcrucialindatascience, MachineLearning, Physics, Engineering 및 Financeduetotheiribility에 대한 handlarge-scaledataefficivally. forexample, Infinancialanyaly

UseanArray.ArrayOveralistInpyThonWhendealingwithhomogeneousData, Performance-CriticalCode, OrinterFacingwithCcode.1) HomogeneousData : ArraysSaveMemorywithtypepletement.2) Performance-CriticalCode : arraysofferbetterporcomanceFornumericalOperations.3) Interf

아니요, NOTALLLISTOPERATIONARESUPPORTEDBYARRARES, andVICEVERSA.1) ArraySDONOTSUPPORTDYNAMICOPERATIONSLIKEPENDORINSERTWITHUTRESIGING, WHITHIMPACTSPERFORMANCE.2) ListSDONOTEECONSTANTTIMECOMPLEXITEFORDITITICCESSLIKEARRAYSDO.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
