'ModuleNotFoundError: No module named aws_cdk

When I run cdk deploy, I get the following error:

Traceback (most recent call last):
  File "app.py", line 3, in <module>
    from aws_cdk import core
ModuleNotFoundError: No module named 'aws_cdk'

I installed cdk with npm

npm install -g aws-cdk

I activated the virtual env by

source .env/bin/activate

I'm using python3.8. I installed aws_cdk dependencies by

pip install -r requirements.txt

When editing the python files, I am able to import aws_cdk and run individual functions successfully. I think the problem is that cdk is located in the /usr directory:

> which cdk
/usr/local/bin/cdk

And I think it's using python from my /usr/bin instead of virtual env. How do I make cdk use python in my virtual environment?

EDIT:

requirements.txt

-e .


Solution 1:[1]

TLDR; .env/bin/pip3.8 install -r requirements.txt solved this same issue at my end

Once you run source .env/bin/activate it actually looks for python libraries on .env/lib/python3.8/site-packages (at least for me!). Thus running cdk ls which calls app.py will looks for aws_cdk in venv site package, not from system site-package as long as "include-system-site-packages = false" under .env/pyvenv.cfg

Solution 2:[2]

I think you have to order

python -m pip install -r requirements.txt

This will install the standard dependencies for your CDK project.

Solution 3:[3]

You have to re-install the aws_cdk in virutal Env. I hope its works

Solution 4:[4]

install via cmd as below.

pip install aws-cdk.core

or

add following line in requirements.txt file

aws-cdk.core

it should resolved

Solution 5:[5]

Came here with the same issue, but as Geremy hints at another reason. On mac, when brew updates the python version it basically breaks your existing virtual environments. The python version that CDK picks isn't the one you necessarily built the virtual environment with.

inserted this into my app.py to get to the bottom of this:

import sys
print(sys.path)

helped tshoot.

Solution 6:[6]

You should run it in virtual environment.

source .env/bin/activate

then

cdk deploy

Solution 7:[7]

I got this error when I moved my directory structure around. I was able to fix it by editing .venv/bin/activate and updating the value of the VIRTUAL_ENV env var.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bigbro
Solution 2 P. Str
Solution 3 Roshin Raphel
Solution 4 Shahabaj S. Shaikh
Solution 5 D. Chapman
Solution 6 user14161182
Solution 7 Geremy