Domanda

Bene, oggi stavo controllando il modulo hashlib in Python, ma poi ho trovato qualcosa che io ancora non riesco a capire.

All'interno di questo modulo Python, v'è un'importazione che non riesco a seguire. Mi fa così:

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

Ho cercato di importare il modulo _sha da una shell Python, ma è sembra che non può essere raggiunto che way.My prima ipotesi è che si tratta di un modulo C, ma non sono sicuro.

Allora dimmi ragazzi, sai dov'è quel modulo? Come fanno a importarlo?

È stato utile?

Soluzione

In realtà, il modulo _sha è fornita da shamodule.c e _md5 è fornita da md5module.c e md5.c ed entrambi saranno costruiti solo quando il Python non viene compilato con OpenSSL per impostazione predefinita.

È possibile trovare i dettagli nel setup.py nel vostro tarball Python Source.

    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']) )

Il più delle volte, il vostro Python è costruito con libreria OpenSSL e in tal caso, queste funzioni sono forniti dalle librerie OpenSSL stesso.

Ora, se li volete a parte, allora si può costruire il vostro Python senza OpenSSL o meglio ancora, è possibile costruire l'opzione pydebug con e li hanno.

Dal vostro tarball Python Fonte:

./configure --with-pydebug
make

E ci si va:

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

Altri suggerimenti

Sembra che si sta installazione Python ha sha compilato all'interno _haslib invece di _sha (entrambi i moduli C). Da hashlib.py in Python 2.6:

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')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top