[英]Encoding passed argument for serial.write python
I am trying to send some data by an xbee from pc to arduino. 我试图通过xbee从PC发送一些数据到arduino。
I have a test packet which I know it well built which is: 我有一个测试数据包,我知道它构建良好,它是:
7E 00 7D 33 10 01 00 7D 33 A2 00 40 69 76 DD FF FE 00 00 01 52 B8 DA 41 1A
If I use: 如果我使用:
ser.write(b'\x7E\x00\x7D\x33\x10\x01\x00\x7D\x33\xA2\x00\x40\x69\x76\xDD\xFF\xFE\x00\x00\x01\x52\xB8\xDA\x41\x1A')
My packet arrives to arduino. 我的包裹到达了arduino。
But now I want to pass this packet by command line. 但是现在我想通过命令行传递此数据包。 Something like:
就像是:
python test.py '\x7E\x00\x7D\x33\x10\x01\x00\x7D\x33\xA2\x00\x40\x69\x76\xDD\xFF\xFE\x00\x00\x01\x52\xB8\xDA\x41\x1A'
Being able this way to change data every time I want. 能够通过这种方式每次更改数据。
I tried with: 我尝试了:
ser.write(sys.argv[1])
ser.write(sys.argv[1].encode('ascii'))
And other tries but always fails. 和其他尝试,但总是失败。
Any idea about how I have to pass the data? 关于如何传递数据的任何想法吗? I think the problem is related to the initial b in ser.write...
我认为问题与ser.write中的初始b有关...
I am using python 2.6 or 2.7... Not 3. 我正在使用python 2.6或2.7 ...不是3。
This works, but I have a feeling there's a better solution (there was; see the edit) : 这可行,但是我感觉有更好的解决方案(有;请参见编辑) :
import ast
import sys
ser.write(ast.literal_eval("'{0}'".format(sys.argv[1])))
We use the safe literal_eval
from the ast
module to evaulate the string "'\\x7E\\x00\\x7D...'"
as a python literal, which gets us what we want. 我们使用安全
literal_eval
从ast
模块evaulate字符串"'\\x7E\\x00\\x7D...'"
作为一个python的文本,这得到我们想要的东西。
EDIT: Ah- hah! 编辑:啊! Found a better solution here :
在这里找到了更好的解决方案:
ser.write(sys.argv[1].decode("string-escape"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.