How to connect a BME680?

I remove bme680.pyc and bme680-client.py files and that it looks:

pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ ls
bensimmo.py             Example-02-ReceiveData.py    Example-04-SendDataOnTrigger.py  read-cayenne.py.save
Example-01-SendData.py  Example-03-CayenneClient.py  read-cayenne.py                  test_bme680.py
pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ python test_bme680.py
read-all.py - Displays temperature, pressure, humidity, and gas.
Press Ctrl+C to exit!

Connecting to mqtt.mydevices.com:8883
Calibration data:
par_gh1: -51
par_gh2: -12741
par_gh3: 18
par_h1: 880
par_h2: 990
par_h3: 0
par_h4: 45
par_h5: 20
par_h6: 120
par_h7: -100
par_p1: 37570
par_p10: 30
par_p2: -10627
par_p3: 88
par_p4: 6075
par_p5: -104
par_p6: 30
par_p7: 68
par_p8: -5847
par_p9: -1284
par_t1: 26188
par_t2: 26263
par_t3: 3
range_sw_err: 0
res_heat_range: 1
res_heat_val: 42
t_fine: 117248


Initial reading:
gas_index: 0
gas_resistance: 11272345
heat_stable: False
humidity: 40.499
meas_index: 0
pressure: 1011.86
status: 32
temperature: 22.9


Polling:
Connected with result code 0
SUB v1/06487d60-1537-11ea-84bb-8f71124cfdfb/things/79503770-153d-11ea-a38a-d57172a4b4d4/cmd/+
PUB v1/06487d60-1537-11ea-84bb-8f71124cfdfb/things/79503770-153d-11ea-a38a-d57172a4b4d4/sys/model Python
PUB v1/06487d60-1537-11ea-84bb-8f71124cfdfb/things/79503770-153d-11ea-a38a-d57172a4b4d4/sys/version 1.1.0
Traceback (most recent call last):
  File "test_bme680.py", line 79, in <module>
    client.celsiusWrite(1, bme_sensor.data.temperature)
NameError: name 'bme_sensor' is not defined
pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ 

can you copy and paste the test_bme680.py code here.

test_bme680.py

#!/usr/bin/env python

import cayenne.client
import time
import logging

import bme680
import time

# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
MQTT_USERNAME  = "06487d60-1537-11ea-84bb-8f71124cfdfb"
MQTT_PASSWORD  = "23309cdee31964b2ae4caed9417b689c9bebece2"
MQTT_CLIENT_ID = "79503770-153d-11ea-a38a-d57172a4b4d4"

print("""read-all.py - Displays temperature, pressure, humidity, and gas.
Press Ctrl+C to exit!
""")
client = cayenne.client.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, loglevel=logging.INFO, port=8883)
# For a secure connection use port 8883 when calling client.begin:
# client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883, loglevel=logging.INFO)

i=0
timestamp = 0

try:
    sensor = bme680.BME680(bme680.I2C_ADDR_PRIMARY)
except IOError:
    sensor = bme680.BME680(bme680.I2C_ADDR_SECONDARY)

# These calibration data can safely be commented
# out, if desired.

print('Calibration data:')
for name in dir(sensor.calibration_data):

    if not name.startswith('_'):
        value = getattr(sensor.calibration_data, name)

        if isinstance(value, int):
print('{}: {}'.format(name, value))

# These oversampling settings can be tweaked to
# change the balance between accuracy and noise in
# the data.

sensor.set_humidity_oversample(bme680.OS_2X)
sensor.set_pressure_oversample(bme680.OS_4X)
sensor.set_temperature_oversample(bme680.OS_8X)
sensor.set_filter(bme680.FILTER_SIZE_3)
sensor.set_gas_status(bme680.ENABLE_GAS_MEAS)

print('\n\nInitial reading:')
for name in dir(sensor.data):
    value = getattr(sensor.data, name)

    if not name.startswith('_'):
        print('{}: {}'.format(name, value))

sensor.set_gas_heater_temperature(320)
sensor.set_gas_heater_duration(150)
sensor.select_gas_heater_profile(0)

# Up to 10 heater profiles can be configured, each
# with their own temperature and duration.
# sensor.set_gas_heater_profile(200, 150, nb_profile=1)
# sensor.select_gas_heater_profile(1)

print('\n\nPolling:')
try:
    while True:
        client.loop()
        if (time.time() > timestamp + 10):
            if sensor.get_sensor_data():
                output = '{0:.2f} C,{1:.2f} hPa,{2:.2f} %RH'.format(
                    sensor.data.temperature,
                    sensor.data.pressure,
                    sensor.data.humidity)
                client.celsiusWrite(1, bme_sensor.data.temperature)
                client.hectoPascalWrite(2, bme_sensor.data.pressure)
                client.virtualWrite(3, bme_sensor.data.humidity,"rel_hum","p")

                if sensor.data.heat_stable:
                    print('{0},{1} Ohms'.format(
                        output,
                        sensor.data.gas_resistance))
                    client.virtualWrite(4, sensor.data.gas_resistance, "co","ohms")
                else:
                    print(output)


except KeyboardInterrupt:
    pass

let try this:

run this command in your pi terminal:

pip3 install adafruit-circuitpython-lis3dh
pip3 install adafruit-circuitpython-bme680

and then change the code to:

import cayenne.client
import time
import logging

from busio import I2C
import adafruit_bme680
import time
import board

# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
MQTT_USERNAME  = "MQTT_USERNAME"
MQTT_PASSWORD  = "MQTT_PASSWORD"
MQTT_CLIENT_ID = "MQTT_CLIENT_ID"


client = cayenne.client.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, loglevel=logging.INFO)
# For a secure connection use port 8883 when calling client.begin:
# client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883, loglevel=logging.INFO)

i=0
timestamp = 0

# Create library object using our Bus I2C port
i2c = I2C(board.SCL, board.SDA)
bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c)

# change this to match the location's pressure (hPa) at sea level
bme680.sea_level_pressure = 1013.25

while True:
    client.loop()

    if (time.time() > timestamp + 10):
#        client.celsiusWrite(5, i)
        client.celsiusWrite(1, bme680.temperature)
        client.hectoPascalWrite(2, bme680.pressure)
        client.virtualWrite(3, bme680.humidity,"rel_hum","p")
        client.virtualWrite(4, bme680.gas, "co","ohms")
        timestamp = time.time()
        i = i+1

That is the whole code for bme680.py file or I have to combine something? Because only that code give me error:

Traceback (most recent call last):
  File "test_bme680.py", line 7, in <module>
    from busio import I2C
ImportError: No module named busio

did you run this command?

Yes I run:

pip3 install adafruit-circuitpython-lis3dh
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting adafruit-circuitpython-lis3dh
  Downloading https://www.piwheels.org/simple/adafruit-circuitpython-lis3dh/adafruit_circuitpython_lis3dh-5.0.1-py3-none-any.whl
Collecting Adafruit-Blinka (from adafruit-circuitpython-lis3dh)
  Downloading https://www.piwheels.org/simple/adafruit-blinka/Adafruit_Blinka-3.1.0-py3-none-any.whl (79kB)
    100% |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 81kB 406kB/s 
Collecting Adafruit-PureIO (from Adafruit-Blinka->adafruit-circuitpython-lis3dh)
  Downloading https://www.piwheels.org/simple/adafruit-pureio/Adafruit_PureIO-0.2.3-py3-none-any.whl
Collecting spidev>=3.4; sys_platform == "linux" (from Adafruit-Blinka->adafruit-circuitpython-lis3dh)
  Downloading https://www.piwheels.org/simple/spidev/spidev-3.4-cp37-cp37m-linux_armv6l.whl
Collecting sysv-ipc; platform_system != "Windows" (from Adafruit-Blinka->adafruit-circuitpython-lis3dh)
  Downloading https://www.piwheels.org/simple/sysv-ipc/sysv_ipc-1.0.1-cp37-cp37m-linux_armv6l.whl (68kB)
    100% |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 71kB 211kB/s 
Requirement already satisfied: RPi.GPIO in /usr/lib/python3/dist-packages (from Adafruit-Blinka->adafruit-circuitpython-lis3dh) (0.7.0)
Collecting Adafruit-PlatformDetect (from Adafruit-Blinka->adafruit-circuitpython-lis3dh)
  Downloading https://www.piwheels.org/simple/adafruit-platformdetect/Adafruit_PlatformDetect-1.3.8-py3-none-any.whl
Collecting rpi-ws281x>=4.0.0 (from Adafruit-Blinka->adafruit-circuitpython-lis3dh)
  Downloading https://www.piwheels.org/simple/rpi-ws281x/rpi_ws281x-4.2.2-cp37-cp37m-linux_armv6l.whl (104kB)
    100% |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 112kB 382kB/s 
Installing collected packages: Adafruit-PureIO, spidev, sysv-ipc, Adafruit-PlatformDetect, rpi-ws281x, Adafruit-Blinka, adafruit-circuitpython-lis3dh
Successfully installed Adafruit-Blinka-3.1.0 Adafruit-PlatformDetect-1.3.8 Adafruit-PureIO-0.2.3 adafruit-circuitpython-lis3dh-5.0.1 rpi-ws281x-4.2.2 spidev-3.4 sysv-ipc-1.0.1
pi@raspberrypi:~ $ pip3 install adafruit-circuitpython-bme680
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting adafruit-circuitpython-bme680
  Downloading https://www.piwheels.org/simple/adafruit-circuitpython-bme680/adafruit_circuitpython_bme680-3.1.1-py3-none-any.whl
Requirement already satisfied: Adafruit-Blinka in ./.local/lib/python3.7/site-packages (from adafruit-circuitpython-bme680) (3.1.0)
Collecting adafruit-circuitpython-busdevice (from adafruit-circuitpython-bme680)
  Downloading https://www.piwheels.org/simple/adafruit-circuitpython-busdevice/adafruit_circuitpython_busdevice-4.0.1-py3-none-any.whl
Requirement already satisfied: RPi.GPIO in /usr/lib/python3/dist-packages (from Adafruit-Blinka->adafruit-circuitpython-bme680) (0.7.0)
Requirement already satisfied: Adafruit-PureIO in ./.local/lib/python3.7/site-packages (from Adafruit-Blinka->adafruit-circuitpython-bme680) (0.2.3)
Requirement already satisfied: sysv-ipc; platform_system != "Windows" in ./.local/lib/python3.7/site-packages (from Adafruit-Blinka->adafruit-circuitpython-bme680) (1.0.1)
Requirement already satisfied: rpi-ws281x>=4.0.0 in ./.local/lib/python3.7/site-packages (from Adafruit-Blinka->adafruit-circuitpython-bme680) (4.2.2)
Requirement already satisfied: Adafruit-PlatformDetect in ./.local/lib/python3.7/site-packages (from Adafruit-Blinka->adafruit-circuitpython-bme680) (1.3.8)
Requirement already satisfied: spidev>=3.4; sys_platform == "linux" in ./.local/lib/python3.7/site-packages (from Adafruit-Blinka->adafruit-circuitpython-bme680) (3.4)
Installing collected packages: adafruit-circuitpython-busdevice, adafruit-circuitpython-bme680
Successfully installed adafruit-circuitpython-bme680-3.1.1 adafruit-circuitpython-busdevice-4.0.1

did you use python or python3 to run the code?

I use python
on python3:

pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ python3 test_bme680.py 
Traceback (most recent call last):
  File "test_bme680.py", line 3, in <module>
    import cayenne.client
ModuleNotFoundError: No module named 'cayenne'

run this command and try again:

cd Cayenne-MQTT-Python
python3 setup.py install
pi@raspberrypi:~/Cayenne-MQTT-Python $ sudo python3 setup.py install
running install
running bdist_egg
running egg_info
writing cayenne_mqtt.egg-info/PKG-INFO
writing dependency_links to cayenne_mqtt.egg-info/dependency_links.txt
writing requirements to cayenne_mqtt.egg-info/requires.txt
writing top-level names to cayenne_mqtt.egg-info/top_level.txt
reading manifest file 'cayenne_mqtt.egg-info/SOURCES.txt'
writing manifest file 'cayenne_mqtt.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-armv6l/egg
running install_lib
running build_py
creating build/lib
creating build/lib/cayenne
copying cayenne/client.py -> build/lib/cayenne
copying cayenne/__init__.py -> build/lib/cayenne
creating build/bdist.linux-armv6l/egg
creating build/bdist.linux-armv6l/egg/cayenne
copying build/lib/cayenne/client.py -> build/bdist.linux-armv6l/egg/cayenne
copying build/lib/cayenne/__init__.py -> build/bdist.linux-armv6l/egg/cayenne
byte-compiling build/bdist.linux-armv6l/egg/cayenne/client.py to client.cpython-37.pyc
byte-compiling build/bdist.linux-armv6l/egg/cayenne/__init__.py to __init__.cpython-37.pyc
creating build/bdist.linux-armv6l/egg/EGG-INFO
copying cayenne_mqtt.egg-info/PKG-INFO -> build/bdist.linux-armv6l/egg/EGG-INFO
copying cayenne_mqtt.egg-info/SOURCES.txt -> build/bdist.linux-armv6l/egg/EGG-INFO
copying cayenne_mqtt.egg-info/dependency_links.txt -> build/bdist.linux-armv6l/egg/EGG-INFO
copying cayenne_mqtt.egg-info/requires.txt -> build/bdist.linux-armv6l/egg/EGG-INFO
copying cayenne_mqtt.egg-info/top_level.txt -> build/bdist.linux-armv6l/egg/EGG-INFO
zip_safe flag not set; analyzing archive contents...
creating 'dist/cayenne_mqtt-1.1.0-py3.7.egg' and adding 'build/bdist.linux-armv6l/egg' to it
removing 'build/bdist.linux-armv6l/egg' (and everything under it)
Processing cayenne_mqtt-1.1.0-py3.7.egg
Copying cayenne_mqtt-1.1.0-py3.7.egg to /usr/local/lib/python3.7/dist-packages
Adding cayenne-mqtt 1.1.0 to easy-install.pth file

Installed /usr/local/lib/python3.7/dist-packages/cayenne_mqtt-1.1.0-py3.7.egg
Processing dependencies for cayenne-mqtt==1.1.0
Searching for paho-mqtt==1.5.0
Best match: paho-mqtt 1.5.0
Processing paho_mqtt-1.5.0-py3.7.egg
paho-mqtt 1.5.0 is already the active version in easy-install.pth

Using /usr/local/lib/python3.7/dist-packages/paho_mqtt-1.5.0-py3.7.egg
Finished processing dependencies for cayenne-mqtt==1.1.0
pi@raspberrypi:~/Cayenne-MQTT-Python $ cd examples/
pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ ls
Example-01-SendData.py  Example-02-ReceiveData.py  Example-03-CayenneClient.py  Example-04-SendDataOnTrigger.py  test_bme680.py
pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ python3 test_bme680.py
Connecting to mqtt.mydevices.com:1883
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_bus_device/i2c_device.py", line 68, in __init__
    i2c.writeto(device_address, b'')
  File "/home/pi/.local/lib/python3.7/site-packages/busio.py", line 82, in writeto
    return self._i2c.writeto(address, buffer, stop=stop)
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_blinka/microcontroller/generic_linux/i2c.py", line 38, in writeto
    self._i2c_bus.write_bytes(address, buffer[start:end])
  File "/home/pi/.local/lib/python3.7/site-packages/Adafruit_PureIO/smbus.py", line 244, in write_bytes
    self._device.write(buf)
OSError: [Errno 121] Remote I/O error

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_bus_device/i2c_device.py", line 74, in __init__
    i2c.readfrom_into(device_address, result)
  File "/home/pi/.local/lib/python3.7/site-packages/busio.py", line 72, in readfrom_into
    return self._i2c.readfrom_into(address, buffer, stop=stop)
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_blinka/microcontroller/generic_linux/i2c.py", line 44, in readfrom_into
    readin = self._i2c_bus.read_bytes(address, end-start)
  File "/home/pi/.local/lib/python3.7/site-packages/Adafruit_PureIO/smbus.py", line 155, in read_bytes
    return self._device.read(number)
OSError: [Errno 121] Remote I/O error

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test_bme680.py", line 28, in <module>
    bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c)
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_bme680.py", line 348, in __init__
    self._i2c = i2c_device.I2CDevice(i2c, address)
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_bus_device/i2c_device.py", line 76, in __init__
    raise ValueError("No I2C device at address: %x" % device_address)
ValueError: No I2C device at address: 77
pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ sudo python3 test_bme680.py
Traceback (most recent call last):
  File "test_bme680.py", line 7, in <module>
    from busio import I2C
ModuleNotFoundError: No module named 'busio'
pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ python test_bme680.py
Traceback (most recent call last):
  File "test_bme680.py", line 7, in <module>
    from busio import I2C
ImportError: No module named busio
pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ 

can you try this code with python3.

It’s above.

pi@raspberrypi:~/Cayenne-MQTT-Python/examples $ python3 test_bme680.py
Connecting to mqtt.mydevices.com:1883
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_bus_device/i2c_device.py", line 68, in __init__
    i2c.writeto(device_address, b'')
  File "/home/pi/.local/lib/python3.7/site-packages/busio.py", line 82, in writeto
    return self._i2c.writeto(address, buffer, stop=stop)
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_blinka/microcontroller/generic_linux/i2c.py", line 38, in writeto
    self._i2c_bus.write_bytes(address, buffer[start:end])
  File "/home/pi/.local/lib/python3.7/site-packages/Adafruit_PureIO/smbus.py", line 244, in write_bytes
    self._device.write(buf)
OSError: [Errno 121] Remote I/O error

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_bus_device/i2c_device.py", line 74, in __init__
    i2c.readfrom_into(device_address, result)
  File "/home/pi/.local/lib/python3.7/site-packages/busio.py", line 72, in readfrom_into
    return self._i2c.readfrom_into(address, buffer, stop=stop)
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_blinka/microcontroller/generic_linux/i2c.py", line 44, in readfrom_into
    readin = self._i2c_bus.read_bytes(address, end-start)
  File "/home/pi/.local/lib/python3.7/site-packages/Adafruit_PureIO/smbus.py", line 155, in read_bytes
    return self._device.read(number)
OSError: [Errno 121] Remote I/O error

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test_bme680.py", line 28, in <module>
    bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c)
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_bme680.py", line 348, in __init__
    self._i2c = i2c_device.I2CDevice(i2c, address)
  File "/home/pi/.local/lib/python3.7/site-packages/adafruit_bus_device/i2c_device.py", line 76, in __init__
    raise ValueError("No I2C device at address: %x" % device_address)
ValueError: No I2C device at address: 77

that’s full code?

is your device detected by pi sudo i2cdetect -y 1

Yes it’s detected and working, give me data in terminal. I have also another working sensor SDS011 on the same Pi zero. I run it with that tutorial

can you just share the code that is working and giving you sensor reading?

That is file read-all.py from folder /bme680/examples/
Installed from github

#!/usr/bin/env python

import bme680
import time

print("""read-all.py - Displays temperature, pressure, humidity, and gas.

Press Ctrl+C to exit!

""")

try:
    sensor = bme680.BME680(bme680.I2C_ADDR_PRIMARY)
except IOError:
    sensor = bme680.BME680(bme680.I2C_ADDR_SECONDARY)

# These calibration data can safely be commented
# out, if desired.

print('Calibration data:')
for name in dir(sensor.calibration_data):

    if not name.startswith('_'):
        value = getattr(sensor.calibration_data, name)

        if isinstance(value, int):
            print('{}: {}'.format(name, value))

# These oversampling settings can be tweaked to
# change the balance between accuracy and noise in
# the data.

sensor.set_humidity_oversample(bme680.OS_2X)
sensor.set_pressure_oversample(bme680.OS_4X)
sensor.set_temperature_oversample(bme680.OS_8X)
sensor.set_filter(bme680.FILTER_SIZE_3)
sensor.set_gas_status(bme680.ENABLE_GAS_MEAS)

print('\n\nInitial reading:')
for name in dir(sensor.data):
    value = getattr(sensor.data, name)

    if not name.startswith('_'):
        print('{}: {}'.format(name, value))

sensor.set_gas_heater_temperature(320)
sensor.set_gas_heater_duration(150)
sensor.select_gas_heater_profile(0)

# Up to 10 heater profiles can be configured, each
# with their own temperature and duration.
# sensor.set_gas_heater_profile(200, 150, nb_profile=1)
# sensor.select_gas_heater_profile(1)

print('\n\nPolling:')
try:
    while True:
        if sensor.get_sensor_data():
            output = '{0:.2f} C,{1:.2f} hPa,{2:.2f} %RH'.format(
                sensor.data.temperature,
                sensor.data.pressure,
                sensor.data.humidity)

            if sensor.data.heat_stable:
                print('{0},{1} Ohms'.format(
                    output,
                    sensor.data.gas_resistance))

            else:
                print(output)

        time.sleep(1)

except KeyboardInterrupt:
    pass

are you using python or python3 to run the code?

python