gpt4 book ai didi

python - 将输入文件从 Excel VBA 发送到 Raspberry Pi 而不更改内容

转载 作者:行者123 更新时间:2023-12-01 09:06:30 26 4
gpt4 key购买 nike

我正在将一个文本文件从 Excel 发送到 Raspberry Pi,Pi 将读取该文件并获取其中的输入。输入只有一行,而且是一个简单的数字,没有其他内容(40,38 等)

当我运行这个宏时,我可以在我的电脑中完美地看到输入文件,但是当我在 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 中使用这个 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

最佳答案

当 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')

关于python - 将输入文件从 Excel VBA 发送到 Raspberry Pi 而不更改内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52006789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com