UnicodeDecodeError:' ascii'编解码器无法解码从pyvisa设备读取的字符串

时间:2017-05-12 21:06:11

标签: python encoding utf-8

所以我使用pyvisa让python与某些乐器交谈。我有这样的代码:

    self.receiver.write("mmem:data? \'traceData.DAT\'")
    sleep(2)
    data_string = self.receiver_visa.read()

写入部分是告诉仪器在哪里找到数据,等待2秒钟才能找到它,然后使用read()实际读取该数据。数据看起来应该是这样的:

'#525817Type;ESU;\r\nVersion;4.73;\r\nDate;10.May 17;\r\nMode;ANALYZER;\r\nCenter Freq;13560000.000000;Hz\r\nFreq Offset;0.000000;Hz\r\nSpan;1000000.000000;Hz\r\nx-Axis;LIN;\r\nStart;13060000.000000;Hz\r\nStop;14060000.000000;Hz\r\nRef Level;-36.000000;dBm\r\nLevel Offset;0.000000;dB\r\nRef Position;100.000000;%\r\ny-Axis;LOG;\r\nLevel Range;100.000000;dB\r\nRf Att;10.000000;dB\r\nRBW;10000.000000;Hz\r\nVBW;30000.000000;Hz\r\nSWT;0.040000;s\r\nTrace Mode;CLR/WRITE;\r\nDetector;MAXPEAK;\r\nSweep Count;0;\r\nTrace 1:;;\r\nx-Unit;Hz;\r\ny-Unit;dBm;\r\nPreamplifier;NOT AVAILABLE;\r\nTransducer;OFF;\r\nValues;625;\r\n13060000;-101.74840545654297;\r\n13061602.564102564;-102.10520935058594;\r\n13063205.128205128;-105.79591369628906;\r\n13064807.692307692;-111.44921875;\r\n13066410.256410256;-106.73763275146484;\r\n13068012.82051282;-105.97975158691406;\r\n13069615.384615384;-103.39719390869....

但是当我运行此代码时,我收到一条错误消息,说明

  

UnicodeDecodeError:' ascii'编解码器不能将字节0xe6解码到位   243:序数不在范围内(128)

所以我认为问题是关于python不使用utf-8。我试着把

#!/usr/bin/env python
# -*- coding: utf-8 -*-

在源代码标题上,但这没有帮助。我做了一些研究,有些人建议做string.decode(' utf-8'),但这对我不起作用,因为我正在直接从pyvisa设备上阅读。有人可以帮忙吗?

TIA

附件是完全追溯:

>>> import pyvisa
>>> rm = pyvisa.ResourceManager()
>>> rm.list_resources()
('TCPIP0::178.168.48.147::inst0::INSTR', 'TCPIP0::178.168.48.21::inst0::INSTR', 'TCPIP0::178.168.48.30::inst0::INSTR', 'ASRL10::INSTR', 'GPIB0::5::INSTR', 'GPIB0::20::INSTR')
>>> maturo = rm.open_resource('GPIB0::20::INSTR')
>>> esu = rm.open_resource('GPIB0::20::INSTR')
>>> esu.query("*IDN?")
'Rohde&Schwarz,ESU-40,100348/040,4.73\n'
>>> esu.write("mmem:del \'traceData.DAT\'")
(26, <StatusCode.success: 0>)
>>> esu.write("mmem:cdir \'D:\'")
(16, <StatusCode.success: 0>)
>>> esu.write("hcop:dev:lang DAT")
(19, <StatusCode.success: 0>)
>>> esu.write("hcop:dest \'mmem\'")
(18, <StatusCode.success: 0>)
>>> esu.write("mmem:stor:trac 1,\'traceData.DAT\'")
(34, <StatusCode.success: 0>)
>>> esu.write("mmem:data? \'traceData.DAT\'")
(28, <StatusCode.success: 0>)
>>> esu.read()
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    esu.read()
  File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyvisa\resources\messagebased.py", line 332, in read
    message = self.read_raw().decode(enco)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 241: ordinal not in range(128)

1 个答案:

答案 0 :(得分:2)

您需要在阅读时指定编码。 MessageBasedResource.read() method采用encoding参数:

ng = self.receiver_visa.read(encoding='latin1')

您需要弄清楚仪器使用的编码,使用MessageBasedResource.read_raw() method来读取二进制数据。

注意,使用错误的编解码器可能会导致Mojibake;特别是Latin-1总是很乐意解码任何二进制数据,但结果文本可能并不清晰。