2011-01-04 5 views
3

글쎄, 오늘은 파이썬에서 hashlib 모듈을 검사하고 있었지만, 그 후에도 여전히 파악할 수없는 것을 발견했습니다._sha import in python hashlib

이 파이썬 모듈 안에는 제가 따라 올 수없는 가져 오기가 있습니다. 나는 이렇게 가고 : 내가 파이썬 쉘에서 _sha 모듈을 가져올 시도

def __get_builtin_constructor(name): 
    if name in ('SHA1', 'sha1'): 
     import _sha 
     return _sha.new 

하지만 way.My 첫번째 추측 그것이 C 모듈 있다는 것을 도달 할 수없는 것 같다,하지만 난 아니에요 확실한.

그럼 모듈을 어디 있는지 아십니까? 어떻게 수입합니까?

답변

8

사실, _sha 모듈이 shamodule.c 및 _md5에 의해 제공됩니다 md5module.c 및 md5.c에 의해 제공되며 파이썬 컴파일되지 않은 경우 모두에만 건설 될 예정 기본적으로 OpenSSL을 사용합니다.

파이썬 소스 tarball에서 setup.py의 세부 정보를 찾을 수 있습니다.

if COMPILED_WITH_PYDEBUG or not have_usable_openssl: 
     # The _sha module implements the SHA1 hash algorithm. 
     exts.append(Extension('_sha', ['shamodule.c'])) 
     # The _md5 module implements the RSA Data Security, Inc. MD5 
     # Message-Digest Algorithm, described in RFC 1321. The 
     # necessary files md5.c and md5.h are included here. 
     exts.append(Extension('_md5', 
         sources = ['md5module.c', 'md5.c'], 
         depends = ['md5.h'])) 

대부분의 경우 Python은 Openssl 라이브러리로 작성되며이 경우 해당 함수는 OpenSSL 라이브러리 자체에서 제공됩니다.

이제 별도로 원한다면 OpenSSL이 없거나 더 나은 Python을 빌드 할 수 있습니다. pydebug 옵션을 사용하여 빌드하고 가져올 수 있습니다. 파이썬 소스 타르볼에서

:

./configure --with-pydebug 
make 

그리고 거기 당신은 간다 : 그래서

>>> import _sha 
[38571 refs] 
>>> _sha.__file__ 
'/home/senthil/python/release27-maint/build/lib.linux-i686-2.7-pydebug/_sha.so' 
[38573 refs] 
5

파이썬 설치가 _sha (두 C 모듈 모두) 대신 _haslib 안에 컴파일 된 것으로 보입니다. 파이썬 2.6 hashlib.py에서 :

import _haslib: 
    ..... 
except ImportError: 
    # We don't have the _hashlib OpenSSL module? 
    # use the built in legacy interfaces via a wrapper function 
    new = __py_new 

    # lookup the C function to use directly for the named constructors 
    md5 = __get_builtin_constructor('md5') 
    sha1 = __get_builtin_constructor('sha1') 
    sha224 = __get_builtin_constructor('sha224') 
    sha256 = __get_builtin_constructor('sha256') 
    sha384 = __get_builtin_constructor('sha384') 
    sha512 = __get_builtin_constructor('sha512') 
+0

, 내가 hashlib 외부에서 해당 모듈 형태의 가져 오기를 할 수있는 방법이? – FernandoEscher

+0

예,'_hashlib'을 가져옵니다 (밑줄을 참고하십시오). '_sha'는'_hashlib'가 설치되어 있지 않은 레거시 인터페이스 인 것 같습니다. 호기심에서 왜 그것을 수입하고 싶습니까? – albertov

+0

나는 호기심 XD이었다. 그러나 지금 나는 그것이 어떻게 작동하는지 알아 낸다! 도와 주셔서 감사합니다! : P – FernandoEscher