Search code examples
pythoncryptographyfernet

Python: 'No module named 'cryptography'' even if calling another function in the same script works


If I call "generateKey" from the script below, everything works fine and the keyfile will be generated. But if I call "cryptkey" the error No module named 'cryptography' will occur.

import cryptography.fernet

def generateKey(keyfile : str):
    key = cryptography.fernet.Fernet.generate_key()

    with open (keyfile, "bw") as fp:
        fp.write (key)

def cryptkey(stringData : str, keyfile : str) -> str:
    symkey = None

    with open (keyfile,"r") as fp:
        symkey = fp.read()

    crypter      = cryptography.fernet.Fernet(symkey)
    crypted_text = crypter.encrypt(stringData.encode())

    return(crypted_text.decode())

I'm working in a virtual environment, with this modules installed:

(venv) E:\Projekte\...>pip list
Package            Version
------------------ ---------
artifactory        0.1.17
certifi            2023.7.22
cffi               1.15.1
charset-normalizer 3.2.0
coverage           7.2.7
cryptography       41.0.3
idna               3.4
oracledb           1.3.2
pathlib            1.0.1
pip                23.2.1
pycparser          2.21
python-dateutil    2.8.2
requests           2.31.0
setuptools         65.5.0
six                1.16.0
urllib3            2.0.4
xmltodict          0.13.0
        
My python-version is
        
(venv) E:\Projekte\...>python --version
    
Python 3.10.11

What did I tried:

  • Reinstalled the module
  • Removed all "pycache" folders
  • Rebooted my computer
  • Removed and reinstalled the virtual environment

Commands and output:

(venv) E:\Projekte...>python -c "import keyFunctions.keyFunctions as kf; kf.generateKey('keyfile.txt')"

(venv) E:\Projekte...>python3 -c "import keyFunctions.keyFunctions as kf; print(kf.cryptkey('blubb', 'keyfile.txt'));"

Traceback (most recent call last): File "", line 1, in File "E:\Projekte...\keyFunctions\keyFunctions.py", line 1, in from cryptography import fernet ModuleNotFoundError: No module named 'cryptography'


Solution

  • The solution is really simple: the problem sits in front of the computer. It was the call of python3, which calls the python-executable outside the virtual environment, instead the python inside the venv. And because I'm not installing any modules in the global environment, the missing module couldn't be found!

    Thx to @bereal