【问题标题】:Weird Python output when printing打印时奇怪的 Python 输出
【发布时间】:2017-07-10 18:26:32
【问题描述】:

我对 python 很陌生,我正在尝试使用 LibMPSSE 库从霍尼韦尔差压传感器读取压力数据。我正在从 Adafruit FT232H 芯片读取它,并且我在 ubuntu Linux 上使用 python 2.7.6。

#!/usr/bin/env python


from mpsse import *

SIZE = 2    # 2 bytes MSB first
WCMD = "\x50"   # Write start address command
RCMD = "\x51"       # Read command
FOUT = "eeprom.txt" # Output file

try:
    eeprom = MPSSE(I2C)

    # print "%s initialized at %dHz (I2C)" % (eeprom.GetDescription(), eeprom.GetClock())

    eeprom.Start()
    eeprom.Write(WCMD)
    # Send Start condition to i2c-slave (Pressure Sensor)
    if eeprom.GetAck() == ACK:
        # ACK received,resend START condition and set R/W bit to 1 for read 
        eeprom.Start()
        eeprom.Write(RCMD)

        if eeprom.GetAck() == ACK:
            # ACK recieved, continue supply the clock to slave
            data = eeprom.Read(SIZE)
            eeprom.SendNacks()
            eeprom.Read(1)
        else:
            raise Exception("Received read command NACK2!")
    else:
        raise Exception("Received write command NACK1!")

    eeprom.Stop()
    print(data)
    eeprom.Close()

except Exception, e:
    print "MPSSE failure:", e

根据库,Read 返回一个大小字节的字符串,每当我想打印数据时,我看到的唯一输出是 ����2��T_`ʋ�Q}�*/�eE� .我已经尝试使用 utf-8 进行编码,但仍然没有成功。

【问题讨论】:

  • 我对这个库没有任何经验。尝试在最后一个 print(data) 之后添加 print(type(data))print(','.join(['{:d}'.format(x) for x in map(ord, data)])),以查看数据是什么以及它包含什么。
  • @AGNGazer 它输出: 6,94。你能解释一下 print(','.join(['{:d}'.format(x) for x in map(ord, data)])) 的作用吗?
  • 该长语句本质上是用于打印与data 字符串中的每个字符串字符相对应的逗号分隔的 ASCII 值。所以,您的数据字符串似乎只包含 2 个字符...这是您所期望的吗?
  • 如果您想以十六进制打印这两个字节的内容,请执行以下操作:print(','.join(['{:02X}'.format(x) for x in map(ord, data)]))
  • @AGNGazer 感谢您的帮助!是的,我希望读取 2 个字节,这些值是我在使用更高级别的库读取压力数据时得到的确切值。我想知道是否有办法将这两个数据值组合成一个 2 字节值?或者我如何将这两个值放入不同的变量中?

标签: python python-2.7 ftdi


【解决方案1】:

当字符串中的字节/字符(在您的情况下为data)包含不可打印字符时,Python 可能会打印“奇怪”的输出。要“查看”单个字节的内容(作为整数或十六进制),请执行以下操作:

print(','.join(['{:d}'.format(x) for x in map(ord, data)])) # decimal

print(','.join(['{:02X}'.format(x) for x in map(ord, data)]))

由于data 缓冲区的长度是由SIZE=2 设置的,因此要从该缓冲区中提取每个字节为整数,您可以执行以下操作:

hi, lo = map(ord, data)
# or:
hi = ord(data[0])
lo = ord(data[1])

要了解更多关于 ord 及其作用的信息 - 请参阅 https://docs.python.org/2/library/functions.html#ord

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-30
    • 2017-12-29
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多