简体   繁体   中英

Python KeyError when printing a string

I'm trying to print a string via stdout in Python which will then be picked up by through a child process in NodeJS. My code is as follows:

sys.stdout.write('{r: {0}, g: {1}, b: {2}, brightness: {3}}'.format(int(result_color.color[0]), int(result_color.color[1]), int(result_color.color[2]), int(current_brightness)))
sys.stdout.flush()

but for some reason I get the following error:

Traceback (most recent call last):
  File "C:\..\script.py", line 811, in <module>
    main(sys.argv[1:])
  File "C:\..\script.py", line 756, in main
    sys.stdout.write('{r: {0}, g: {1}, b: {2}, brightness: {3}}'.format(int(result_color.color[0]), int(result_color.color[1]), int(result_color.color[2]), int(current_brightness)))
KeyError: 'r'

I can surround the keys with a " ' " but then it is not in the correct format to use JSON.parse() through JS. Why is it exhibiting this behavior? It can't think of a reason for it to be trying to process it as a dictionary when I'm passing print a string. (I want to process this as a string through Python and an Object once received in JS. A dict shouldn't be involved on Python's endd)

{ and } is the key characters in a string template, you have to escape it with {{ and }} , Try

sys.stdout.write('{{r: {0}, g: {1}, b: {2}, brightness: {3}}}'.format(int(result_color.color[0]), int(result_color.color[1]), int(result_color.color[2]), int(current_brightness)))

You can find more information here: https://docs.python.org/3/library/string.html#format-string-syntax

If you use Python 3.x You can use f-string for fomatting, I think it's more readable

import sys;

class Color:
  def __init__(self, rgb, brightness):
    self.color = rgb
    self.brightness = brightness;

result_color = Color([11,22,33], 100)    

def show_color(color, brightness):
  [r,g,b] = color;
  sys.stdout.write(f'r: {r}, g: {g}, b: {b}, brightness: {brightness}\n')
  sys.stdout.flush()

show_color(result_color.color, result_color.brightness)

Here's an expanded version of my comment. It uses the builtin json module. I've also shortened the code so it looks neater and doesn't repeat as much.

import sys
import json

...

r, g, b = map(int, result_color.color)
data = dict(r=r, g=g, b=b)

sys.stdout.write(json.dumps(data))
sys.stdout.flush()

Also, I suggest that you use the normal print function. If you need to not have a newline at the end and you want to flush it, both are parameters you can specify.

print(json.dumps(data), end="", flush=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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