'Python "No module named mysql.connector" when running script on Raspberry Pi

I wrote a Python script to test the MariaDB package using Python-3.7.3 running on a Raspberry Pi 3. The script is shown below:

    #============================================================================  
    # Test Snippet #1
    
    import mysql.connector
    
    from mysql.connector
    import connect, errorcode, Error
    
    ############################################################################
    # Begin execution here:
    print (">> Program Start >>")
    
    #---------------------------------------------------------------------------
    # Connect to the test database:
    try:
        dbConn=\  
            connect (user='WebServer', password='$$$$$$$$', host='localhost', \  
                database='HamRadio')  
    except Error as err:  
        print ("! Error #", err.errno, \  
             " encountered when connecting to test database !")  
    #---------------------------------------------------------------------------  
    # Search the test table for certain entries:  
    curSel=dbConn.cursor ()  
    strStatement="SELECT * FROM HamRadio.Log WHERE Call_Sign like 'OK%' " + \
        "ORDER BY Call_Sign"  
    try:  
        curSel.execute (strStatement)    
    except Error as err:  
        print ("! Error #", err.errno, " encountered when executing SELECT command !")  
    #---------------------------------------------------------------------------  
    # Display the rows selected:  
    for row in curSel:    
        print ("Row Contents=", row)   
    #---------------------------------------------------------------------------  
    # Close the database table:  
    curSel.close ()  

If I execute this script using the Python3 IDE (Python shell), the script works correctly.

However, if I attempt to execute the same script from the command line:

pi@raspberrypi:~ $ sudo python TestSnippet_1.py

The following error message is displayed:

'''

Traceback (most recent call last):
  File "TestSnippet_1.py", line 4, in <module>
    import mysql.connector
ImportError: No module named mysql.connector*

''' I suspect that the issue may be related to some sort of environment path but I lack the experience using Python in a Raspberry Pi environment to fully understand what is happening.

Any help would greatly be appreciated because I am at a standstill at this point.



Solution 1:[1]

After many hours of investigation, I determined that the cause of the error was the use of 'sudo' in the command line (which invokes a different set of path variables)!! Typing just: python TestSnippet_1.py instead of sudo python TestSnippet_1.py enables the program to execute with no errors!! Very subtle but very deadly!!

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 BitBanger46