2016-10-18 3 views
2

/home/kurt/dev/clones/ipercron-utils/tester 디렉토리에 파이썬 모듈을 가져 오려고합니다. 이 디렉토리에는 tester.pyconfig.yml 파일이 있습니다. tester.py 다른 디렉토리에서, 나는 그렇게처럼 가져 오려고, 이제 (선도) 라인다른 디렉토리에서 모듈을 가져 와서 해당 디렉토리에있는 파일을 찾는 방법

config = yaml.safe_load(open("config.yml")) 

을 포함한다 : 그러나

import sys 
sys.path.insert(0, "/home/kurt/dev/clones/ipercron-utils/tester") 
import tester 

, 나는 다음과 같은 오류 얻을 :

Traceback (most recent call last): 
    File "/home/kurt/dev/clones/ipercron-compose/controller/controller_debug2.py", line 9, in <module> 
    import tester 
    File "/home/kurt/dev/clones/ipercron-utils/tester/tester.py", line 28, in <module> 
    config = yaml.safe_load(open("config.yml")) 
IOError: [Errno 2] No such file or directory: 'config.yml' 

내가 이해하는 한, 파이썬은 현재 디렉토리 (/home/kurt/dev/clones/ipercron-compose/controller)에있는 config.yml 파일을 찾고있는 반면에, 모듈의 디렉토리를 살펴보고 싶다. (/home/kurt/dev/clones/ipercron-utils/tester)에서 가져 왔습니다. 이것을 지정하는 방법이 있습니까?

답변

2

__file__에는 항상 현재 모듈 파일 경로 (여기서는 /home/kurt/dev/clones/ipercron-utils/tester/tester.py)가 있습니다.

dirname을 수행하십시오. => 사용자는 yml 구성 파일이있는 경로가 있습니다. 당신의 tester.py 모듈이 같은

코드를 (import os 아직 수행하지 경우) :

module_dir = os.path.dirname(__file__) 
config = yaml.safe_load(open(os.path.join(module_dir,"config.yml"))) 

보조 노트 : 코드가 py2exe에를 사용하여 "컴파일"때 __file__ 메인 파일에서 작동하지 않습니다. 이 경우 다음을 수행해야합니다.

module_dir = os.path.dirname(sys.executable) 
관련 문제