首页 > 解决方案 > 将输入文件从 Excel VBA 发送到 Raspberry Pi,而不更改内容

问题描述

我将一个文本文件从我的 Excel 发送到树莓派,树莓派将读取该文件并在其中获取输入。输入只是一行,它是一个简单的数字,没有别的(40,38 等)

当我运行这个宏时,我可以在我的 PC 中完美地看到输入文件,但是当我在 Pi 中打开它时,它会发生变化,例如:

我的电脑中的输入文件是:

65

Raspberry 中的输入文件是:

ÿþ6

我怎样才能确保这个号码按原样发送给 Pi。或者我如何将其解码为我的 python 脚本可以理解的内容。我不会对这个数字使用小数,如果它作为字符串发送也没关系,因为我可以稍后在我的 python 代码中解析它。

下面是我的 Excel 宏

Sub Send()

    Dim sleeptime As String
    sleeptime = InputBox("Duration between each reading in seconds?")

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim Fileout As Object
    Set Fileout = fso.CreateTextFile("C:\Users\xx\Desktop\VBA\input.txt", True, True)
    Fileout.Write sleeptime
    Fileout.Close
    Set fso = Nothing
    Set Fileout = Nothing


    Const cstrSftp As String = """C:\Program Files\PuTTY\pscp.exe"""
    Dim strCommand As String
    Dim pUser As String
    Dim pPass As String
    Dim pHost As String
    Dim pFile As String
    Dim pRemotePath As String

    pUser = "pi" '//user on remote system
    pPass = "xx" '//user's password on remote system
    pHost = "192.168.x.xx" '//ip address of remote system
    pFile = "C:\Users\xx\Desktop\VBA\input.txt" '//file to transfer
    pRemotePath = "/home/pi/Temp_Codes" '//directory where file will be transferred to

    strCommand = cstrSftp & " -sftp -l " & pUser & " -pw " & pPass & _
        " " & pFile & " " & pHost & ":" & pRemotePath
    Debug.Print strCommand
    Shell strCommand, 0 ' vbHide

End Sub

这些是我使用此输入文件的 Raspberry Pi 脚本中的行。我稍后在 time.sleep 中使用这个睡眠时间值。

with open('input.txt', 'r') as myfile:
    sleeptime = myfile.read()

sleeptime = float(sleeptime.strip())

这是我正在运行的一个简单代码,只是为了测试这个编码:

#!/usr/bin/env python

import io

with io.open('input.txt', 'r', encoding='utf-8-sig') as myfile:
    sleeptime = myfile.read()

sleeptime = float(sleeptime.strip())

这是我到目前为止遇到的错误。

pi@raspberrypi:~/Temp_Codes $ python try.py
Traceback (most recent call last):
  File "try.py", line 6, in <module>
    sleeptime = myfile.read()
  File "/usr/lib/python2.7/codecs.py", line 314, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
  File "/usr/lib/python2.7/encodings/utf_8_sig.py", line 66, in _buffer_decode
    return codecs.utf_8_decode(input, errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

标签: pythonexcelvbaraspberry-pipscp

解决方案


当 Excel/VBA 通过“CreateTextFile”创建 Unicode 文件时,它会将其保存为 UTF-16 编码。您看到的是 BOM(字节顺序标记)。

你可以改变

CreateTextFile("C:\Users\xx\Desktop\VBA\input.txt", True, True)

CreateTextFile("C:\Users\xx\Desktop\VBA\input.txt", True, False)

这将保存为 ASCII 文本文件。或者您可以通过使用在 Pi/Python 端进行更改

open('input.txt', 'r', encoding='utf-16')

推荐阅读