Python'str'对象不支持项目分配

时间:2018-08-02 10:19:53

标签: python string multithreading python-multithreading

我正在为将数据发送到ThingSpeak的嵌入式系统开发python脚本。

为此(并用于研究python),我使用了线程模块,并且还使用了ThingSpeak模块。

基本上我的脚本创建了2个线程:

  • 一个用于每10秒向ThingSpeak发送数据的人。
  • 一个用于切换LED的灯。

除了在ThingSpeak上发布之外,所有其他工作。注意:在没有线程的情况下在thingSpeak上发布。

我收到此错误:“ TypeError:'str'对象不支持项目分配”

Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "thingSpeak.py", line 57, in ThingSpeak_Thread
    response = thingSpeakHandler.update(jsonMessage)
  File "/usr/lib/python2.7/site-packages/thingspeak/thingspeak.py", line 110, in update
    data['api_key'] = self.write_key
TypeError: 'str' object does not support item assignment

我认为此错误与线程的添加有关。

这是我的代码:

import onionGpio
import time
import thingspeak
import sys
import threading
import random
import thread
import json

# Declare variables
heartBeatDelaySec   = 1.0
heartBeatLedStatus  = 0
heartBeatDisable    = False

thingSpeakDelaySec  = 10

thingSpeakChannel = 98765
thingSpeakWriteKey = '1234556'
thingSpeakReadKey = '123456'


def HeartBeatThread( name, delay, runEvent ):
  global heartBeatLedStatus

  print ("Task " + name + " started")

  while runEvent.is_set():
    blueLed.setValue( heartBeatLedStatus )

    if( heartBeatLedStatus == 0 ):
      heartBeatLedStatus = 1
    else:
      heartBeatLedStatus = 0

    time.sleep(delay)

  # Shut-down Led
  blueLed.setValue( 1 )


def ThingSpeak_Thread( name, delay, thingSpeakChannel, thingSpeakWriteKey, runEvent ):

  thingSpeakHandler = thingspeak.Channel( id=thingSpeakChannel, write_key=thingSpeakWriteKey, fmt='json' )

  while runEvent.is_set():
    temp = random.randint(12, 38)
    rH   = random.randint(30, 68)

    # Build JSON with data
    data = {}
    data['1'] = temp
    data['2'] = rH
    jsonMessage = json.dumps(data)

    print( "Publishing: " + jsonMessage )

    response = thingSpeakHandler.update(jsonMessage)

    time.sleep(delay)


# Led Initialize
blueLed   = onionGpio.OnionGpio(15)
greenLed  = onionGpio.OnionGpio(16)
redLed    = onionGpio.OnionGpio(17)

blueLed.setOutputDirection(1)
greenLed.setOutputDirection(1)
redLed.setOutputDirection(1)

blueLed.setValue(1)
greenLed.setValue(1)
redLed.setValue(1)
print ("GPIO configured")


# Initialize Threads
runEvent = threading.Event()
runEvent.set()

heartBeatThreadHandler = threading.Thread(target = HeartBeatThread, args = ("Heart Beat", heartBeatDelaySec, runEvent))

thingSpeakThreadHandler = threading.Thread(target = ThingSpeak_Thread, args = ("ThingSpeak", thingSpeakDelaySec, thingSpeakChannel, thingSpeakWriteKey, runEvent))

# Start Threads
heartBeatThreadHandler.start()
thingSpeakThreadHandler.start()

try:
  while( True ):
    time.sleep(.01)
except:
  print ("Attempting to close threads. Max wait = " + str(max(heartBeatDelaySec, thingSpeakDelaySec)) + "sec")
  runEvent.clear()
  heartBeatThreadHandler.join()
  thingSpeakThreadHandler.join()
  print ("Threads successfully closed")

非常感谢您的帮助。

最好的问候, 费德里科

1 个答案:

答案 0 :(得分:1)

函数json.dumps()中的

ThingSpeak_Thread返回字符串(请参见docs)。然后,您将此 string 传递给thingSpeakHandler.update()方法,但是 期望dict。因此,请删除jsonMessage = json.dumps(data)并将data传递给update()