2014-05-25 2 views
0

다음 중 올바른 Python 2.7 가져 오기 시나리오는 무엇입니까? 즉, stdlib 모듈을 섀도 잉하는 이름의 모듈을 가지고 있다면 import <module> stdlib 또는 로컬 버전을 가져와야합니까? OSX에서 Python 절대 가져 오기

$ ls 
__init__.py time.py 

~/tmp $ cat time.py 
def a(): 
    print(¨a¨) 

~/tmp $ python 
Python 2.7.4 (default, Sep 26 2013, 03:20:26) 
[GCC 4.7.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import time 
>>> dir(time) 
['__doc__', '__name__', '__package__', 'accept2dyear', 'altzone', 'asctime',  'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset'] 

와 OSX

에 리눅스

sdk$ ls 
__init__.py time.py  time.pyc 

$ cat time.py 
def a(): 
    print("a") 

$ python 
Python 2.7.6 (default, Apr 9 2014, 11:48:52) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import time 
>>> dir(time) 
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a'] 

PS : 윈도우 리눅스 따라 보인다 __future__ import absolute_import에서 사용하는 현재 경로가 보통에 추가됩니다

+0

두 OS 모두 파이썬 경로에 모듈이 포함되어 있습니까? – jonrsharpe

+0

첫 번째 예제에서'~/tmp'로 cd하지 않았습니까? 거기에'__init __. py'가 있습니까? – juanchopanza

+0

왜 같은 이름의 모듈을 사용하고 있습니까? –

답변

1

영향을주지 않습니다 목록의 첫 번째 위치 sys.path. 즉, 사용자 정의 모듈을 항상 가져옵니다.

원하지 않는 경우 python -E 모드에서 인터프리터를 시작할 수 있습니다. 현재 경로가 sys.path이 아니므로 기본 모듈이로드됩니다.

전역 모듈을 가져올 수있는 또 다른 방법은, 당신이

어디에 당신을 제공 약간의 해킹이 당신이 가져올 때 다른 디렉토리에있어, 및 가져 오기 후 보일 수

import os 

temp_path = os.getcwd() 
os.chdir('/some/other/path') 

import myshadowingmodule 
os.chdir(temp_path) 

을하는 것입니다

또한 두 가지 기능이 있습니다. __import__importlib.import_module - 궁금한 점이 있다면 섀도 잉 된 모듈을 가져 오는 데 사용할 수 없습니다.