How do I fix modulenotfounderror: no module named 'distutils' when running a Python script?

I’m trying to run a Python script, but I keep getting this error:

modulenotfounderror: no module named 'distutils'

I thought distutils was included with Python by default, but it seems like it’s missing from my environment. I’m using Python 3.x on Linux (Ubuntu), and I installed Python via apt.

Has anyone dealt with this modulenotfounderror: no module named distutils issue before?

What’s the recommended way to install or restore the distutils module so I can continue working with setup tools and packages that depend on it?

This usually happens when Python is installed via apt on Ubuntu but the python3-distutils package isn’t included by default. It’s easy to miss, especially if you’re setting up a lightweight or minimal system.

You can fix it by installing the missing system package:

sudo apt-get update
sudo apt-get install python3-distutils

Make sure the version matches your installed Python (e.g., python3.10-distutils if you’re on Python 3.10). Once installed, the error should go away and any package that needs distutils like setuptools, should work as expected.

If you’re building Python from source, distutils doesn’t come bundled like it used to. It’s been deprecated and removed from Python 3.12 onward.

If you’re still on Python <3.12, and you’re compiling from source, make sure you’ve installed libpython3-dev and the relevant ensure pip components before building:

sudo apt-get install libpython3-dev python3-venv python3-pip

Then reconfigure and recompile Python. For recent versions, the alternative is to replace distutils usage with setuptools or packaging. Many newer projects are moving in that direction since distutils is officially deprecated.