Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
KeyError
#1
I have a Keyerror since I have added an new key to my MSG_TXT array. I can't see any format errors in MGS_TXT and when I remove this part the code starts working -" ,""time": {timejb}" My code is:

import datetime
import subprocess
var = "/home"
pipe = subprocess.Popen(["perl","./temper_mon.pl", var], stdout=subprocess.PIPE)
temperature =  pipe.communicate()[0]
print (temperature.decode('utf-8'))
temperature=(temperature.decode('utf-8'))
temperature=temperature.strip('\n')
temperature = float(temperature)
print(type(temperature))
import random
import time

from azure.iot.device import IoTHubDeviceClient, Message

CONNECTION_STRING = "HostName=host;DeviceId=898;SharedAccessKey=keykeykey"

tjb=datetime.datetime.now()
timejb=tjb.strftime("%H:%M:%S")
timejb=str(timejb)
print(type(timejb))
humidity=1
MSG_TXT = '{{"temperature": {temperature},"humidity": {humidity}[b],""time": {timejb}[/b]}}'
print (MSG_TXT)
def iothub_client_init():
    client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
    return client

def iothub_client_telemetry_sample_run():

    try:
        client = iothub_client_init()
        print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )
        while True:


            msg_txt_formatted = MSG_TXT.format(temperature=temperature, humidity=humidity, time=timejb)
I get this error:
Error:
File "./IOTTemperature.py", line 59, in <module> iothub_client_telemetry_sample_run() File "./IOTTemperature.py", line 39, in iothub_client_telemetry_sample_run msg_txt_formatted = MSG_TXT.format(temperature=temperature, humidity=humidity, time=timejb) KeyError: 'timejb'
Reply
#2
Please use the python tags for your code so that we can see the indentation. (And you can put your output in the output tags). Both are available from the buttons above the text box.

You've defined the MSG_TEXT with three elements to pass in: temperature, humidity, and timejb.

But when you call the formatter (on line 37), you instead pass in temperature, humdity, and time. It doesn't know what timejb should be.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020