Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #107680 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2016-04-26 19:58 +0200 |
| Last post | 2016-04-26 19:58 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: How to read from serial port? Peter Otten <__peter__@web.de> - 2016-04-26 19:58 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2016-04-26 19:58 +0200 |
| Subject | Re: How to read from serial port? |
| Message-ID | <mailman.122.1461693520.32212.python-list@python.org> |
David Aldrich wrote:
> Hi
>
> I have written a very simple program to read and print data from the
> serial port using pyserial:
>
> #!/usr/bin/python3
> import serial
>
> ser=serial.Serial('COM1',115200)
> while True:
> out = ser.read()
> print('Receiving...'+out)
>
> When I run it and send data for it to read I get:
>
> C:\SVNProj\Raggio\trunk\hostconsole\gui\prototypes\serial_test>py
> serial_read.py Traceback (most recent call last):
> File "serial_read.py", line 9, in <module>
> print('Receiving...'+out)
> TypeError: Can't convert 'bytes' object to str implicitly
>
> I am using Python 3.5. How would I fix this error please?
Look at the traceback again. The line
> out = ser.read()
is executed, you are reading successfully. What fails is
> print('Receiving...'+out)
You are trying to concatenate a (unicode) string and bytes, like in
>>> print("foo" + b"bar")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'bytes' object to str implicitly
You can avoid that by printing the string and the bytes independently
>>> print("foo", b"bar")
foo b'bar'
If you don't like the b"..." stuff and want to treat the bytes as text
rather than data you can decode them:
>>> print("foo", b"bar".decode())
foo bar
For more see <https://docs.python.org/3/howto/unicode.html>.
Back to top | Article view | comp.lang.python
csiph-web