[Tutor] Converting a string to a byte array
Cameron Simpson
cs at cskk.id.au
Sun Sep 24 20:34:18 EDT 2017
On 25Sep2017 09:29, Phil <phil_lor at bigpond.com> wrote:
>On 25/09/17 07:26, Cameron Simpson wrote:
>>>I don't understand why this works from the pyqt IDE but not when run from
>>>the console. I suppose the IDE is adding the correct encoding.
>>
>>I'm guessing the IDE is python 2 and not doing any encoding at all.
>>In python 2 str _is_ effectively bytes and if you stay in ASCII you
>>just get away with it.
>
>No, the IDE is Eric and as far as I know it's python3 only.
Weird. What if you put your code in try/except in the IDE:
try:
your code here
except BaseException as e:
print("exception: %s" % (e,))
raise
just in case some esoteric exception is being swallowed silently by the IDE.
Not that the error you cite should act that way...
>Just for interest I amended my code to use what you provided and tried it
>under IDLE. There aren't any errors but but my Arduino is not responding.
Weird indeed. Try the try/except above and see if it reveals anything at all.
>However, if I enter python3 mycode.py then it works perfectly. I'm sure
>there's an explanation for this. I have thoney, another python IDE, on a
>raspberrypi I'll try that later and see what the result is. Anyway, it works
>from Eric and from the command prompt.
>
>>So you need to know what your serial device expects. ASCII only?
>
>As it turns out, it doesn't matter if the data is ASCII or UTF-8.
If you're only using ASCII valid characters then the byte sequences are the
same, so you don't really know yet.
>> mytext = "Fred"
>> mytext = mytext + "\n"
>> mybytes = mytext.encode('utf-8')
>> ser.write(mybytes)
>>
>>Notice that I've appended the newline _before_ converting to bytes,
>
>Thank you for the code and the explanation, it's greatly appreciated.
>
>It's all a bit of an anticlimax really. Now that it works I don't know what to
>do with it. Like so many of my projects.
Control something? As a remote to control a TV or PVR, using an IR adapter?
The weather? Courier delivery times? So many possibilities...
Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)
More information about the Tutor
mailing list