Why Cannot You Use a Python Module in a Program or the Command Prompt When One Will Work but Not the Other?

Problem scenario
You have a Python program use an import statement, but the program fails.  From the Python command prompt, you can import the module.  Why is it different?

Possible Solution #1
You may be using Python version 3 for either the command prompt or the program and Python version 2 for the complement (either the command prompt or the program). Try these commands:

python --version
python3 --version

Possible Solution #2
See where the potential imports are. Enter the Python command prompt once with python (or python2) and a second time with python3 (or python). Then run these two commands from that line (where >>> is just a reference a not part of the command itself):

>>> import sys
>>> print(sys.path())

Possible Solution #3
In the Python program, temporarily add these two lines, purely as a diagnostic, before the import line that is causing the problem, and run your program:

import sys

Leave a comment

Your email address will not be published. Required fields are marked *