Coverage.py Python Module - Import Errors when Running Script

I will add my experience, as someone could fall into the same mistake.

I was running coverage inside a python virtual environment (venv) with coverage not installed. Executing coverage I was in fact calling the coverage installed globally.

Installing locally with pip3 install coverage solved it for me, now using python3 -m coverage run myfile.py.


I think I had a similar issue, and managed to solve it by running coverage like this:

python -m coverage run [normal commands]

Specifically in my case it was

python -m coverage run -m unittest discover

It definitely seems to be a case of coverage using a different python installation, as my module that was reported missing was only installed in my virtual env and not in my global env.


The good news is, running with "python" explicitly, and with coverage.py produce the same result. The bad news is, that result is an error message.

It seems like you have more than one Python installation. One is found by "./script_name.py", the other is found by "python ./script_name.py".

To diagnose the problem, add these lines to the top of script_name.py:

import sys
print sys.executable
print "\n".join(sys.path)

This will show you the Python executable being invoked, and the search path for modules. Running your script both ways will show you different results, and you should be able to figure out what is going on.