简体   繁体   English

TypeError:必须为str,而不是字节

[英]TypeError: must be str, not bytes

So I am writing a function that pulls hex color values from a twitter account that posts a color of the day. 因此,我正在编写一个函数,该函数从发布当天颜色的Twitter帐户中提取十六进制颜色值。 I am hoping to send this to an arduino to light up and LED with that color, but I am running into issues when trying to write to the Arduino. 我希望将其发送到arduino并用该颜色的LED点亮,但是在尝试写入Arduino时遇到了问题。 I have converted the hex color value to an RGB value and stored it in a tuple. 我已经将十六进制颜色值转换为RGB值,并将其存储在元组中。 I attempt to reference each value in the RGB tuple to write out of a serial connection to my Arduino, however I cannot encode the integers correctly so that they are sent. 我尝试引用RGB元组中的每个值以写出到Arduino的串行连接,但是我无法正确编码整数,因此无法发送它们。 Here is the specific part of the code I am referring to: 这是我指的代码的特定部分:

 #Convert from hex to rgb
        rgb = tuple(int(this_color[i:i+2], 16) for i in (0, 2 ,4))

        #Add individual rgb values to list
        rgb_values = [rgb[0], rgb[1], rgb[2]]

        if (ser.isOpen()):
        # Start a main loop
            while (loopVar):

                # Prompt for Red value
                redVal = rgb[0]
                print(struct.pack('>B', redVal))
                ser.write("r" + struct.pack('>B',redVal))

                # Prompt for Green value
                greenVal = rgb[1]
                print(struct.pack('>B', greenVal))
                ser.write("g" + struct.pack('>B',greenVal))

                # Prompt for Blue value
                blueVal = rgb[2]
                print(struct.pack('>B', blueVal))
                ser.write("b" + struct.pack('>B',blueVal))

                # Check if user wants to end
                loopCheck = raw_input('Loop (y/N):')
                if (loopCheck == 'N'):
                    loopVar = False

    # After loop exits, close serial connection
    ser.close()

I thought I would need to convert the integer values to raw binary for use in write.serial, but that doesn't seem to be working. 我以为我需要将整数值转换为原始二进制文件,以便在write.serial中使用,但这似乎不起作用。

Here is the output when I run the file: 这是我运行文件时的输出:

142
<class 'int'>
33
<class 'int'>
38
<class 'int'>
b'\x8e'
Traceback (most recent call last):
  File "C:\Users\Louis\Desktop\MSTI Application\Arduino Lamp\Twitter_Scraping_Script_2.py", line 117, in <module>
    get_user_tweets('color_OTD', 5)
  File "C:\Users\Louis\Desktop\MSTI Application\Arduino Lamp\Twitter_Scraping_Script_2.py", line 92, in get_user_tweets
    ser.write("r" + struct.pack('>B',redVal))
TypeError: must be str, not bytes

Any ideas? 有任何想法吗?

Here is the my full code: 这是我的完整代码:

import tweepy 
import csv
import sys
import serial
import struct

#Create Serial port object called arduinoSerialData
ser = serial.Serial("COM1", 57600)
connected = False


#Twitter API credentials
consumer_key = 'xx'
consumer_secret = 'xx'
access_key = 'xx'
access_secret = 'xx'

def get_user_tweets(user_name, num_tweets):
 # Open the Serial Connection
    ser.close()
    ser.open()
    loopVar = True

    #authorize twitter, initialize tweepy
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    #initialize list to hold tweet colors
    tweets_colors = []

    #Initialize string to hold current tweet
    this_tweet = ""

    #Initialize string to hold current color
    this_color = ""

    #Initialize tuple to hold rgb values
    rgb = ()

    #Initialize list to hold rgb values
    rgb_values =[]


    #Call to get access tweets from specified user
    tweets = api.user_timeline(screen_name='color_OTD',count=num_tweets)

    #Create a csv file with the username of the given user
    #with open('%s_tweets.csv' % user_name, 'w', newline='') as f:

        #Create writer object and give csv column names
        #writer = csv.writer(f)
        #writer.writerow(['red','green','blue'])

    #Loop through all tweets accessed
    for tweet in tweets:

        #If the tweet isn't a retweet
        if not tweet.retweeted:

            #Get # with hex color value
            this_tweet = str(tweet.entities.get('hashtags'))

            #Access hex value within hashtag string
            this_color = this_tweet[11:17]

            #Append all colors to list
            tweets_colors.append(this_color)

            #Convert from hex to rgb
            rgb = tuple(int(this_color[i:i+2], 16) for i in (0, 2 ,4))

            #Add individual rgb values to list
            rgb_values = [rgb[0], rgb[1], rgb[2]]
            #Write rgb values to csv
            #writer.writerow(rgb_values)

            print(rgb[0])
            print(type(rgb[0]))
            print(rgb[1])
            print(type(rgb[1]))
            print(rgb[2])
            print(type(rgb[2]))

            if (ser.isOpen()):
            # Start a main loop
                while (loopVar):

                    # Prompt for Red value
                    redVal = rgb[0]
                    print(struct.pack('>B', redVal))
                    ser.write("r" + struct.pack('>B',redVal))

                    # Prompt for Green value
                    greenVal = rgb[1]
                    print(struct.pack('>B', greenVal))
                    ser.write("g" + struct.pack('>B',greenVal))

                    # Prompt for Blue value
                    blueVal = rgb[2]
                    print(struct.pack('>B', blueVal))
                    ser.write("b" + struct.pack('>B',blueVal))

                    # Check if user wants to end
                    loopCheck = raw_input('Loop (y/N):')
                    if (loopCheck == 'N'):
                        loopVar = False

        # After loop exits, close serial connection
        ser.close()





if __name__ == '__main__':
    get_user_tweets('color_OTD', 5)

The reason for your error is that struct returns a bytes string while you are trying to add it to a str type. 发生错误的原因是,在尝试将其添加到str类型时,struct 返回了一个字节字符串 See line ser.write("r" + struct.pack('>B',redVal)) . 参见行ser.write("r" + struct.pack('>B',redVal))

Type "r" + b"r" into a python 3 shell and you will get the same error TypeError: must be str, not bytes . 在python 3 shell中输入"r" + b"r" ,您将得到相同的错误TypeError: must be str, not bytes You need to change "r" to b"r" which turns the string into a bytes string. 您需要将“ r”更改为b“ r”,这会将字符串转换为字节字符串。 https://docs.python.org/3/library/stdtypes.html#bytes https://docs.python.org/3/library/stdtypes.html#bytes

So you will need to change a few of your statements. 因此,您将需要更改一些语句。

ser.write(b"r" + struct.pack('>B',redVal))
ser.write(b"g" + struct.pack('>B',greenVal))
ser.write(b"b" + struct.pack('>B',blueVal))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM