Python 读取并发送多行而不是一行
我有一个Arduino设置和一个迷你显示。它已编程,因此我在串行“命令行”中键入的任何内容都将打印到显示器上 食品.txtPython 读取并发送多行而不是一行,python,python-3.x,arduino,Python,Python 3.x,Arduino,我有一个Arduino设置和一个迷你显示。它已编程,因此我在串行“命令行”中键入的任何内容都将打印到显示器上 食品.txt First Line First Line Second Line Third Line Fourth Line 如果txt文件只有一行,则此操作很好 import serial import time f = open("Foods.txt", "r") lines = f.readline() for line in lines
First Line
First Line
Second Line
Third Line
Fourth Line
如果txt文件只有一行,则此操作很好
import serial
import time
f = open("Foods.txt", "r")
lines = f.readline()
for line in lines:
ser = serial.Serial('/dev/cu.SLAB_USBtoUART', 115200, timeout = 1)
commandToSend = lines
ser.write(str(commandToSend).encode()).
输出如下:
First Line
如果我在Foods.txt中添加行
First Line
First Line
Second Line
Third Line
Fourth Line
我得到这个输出(第一行11次):
如果我将“f.readlines()”更改为lines,而不是line,以便逐个读取多行,它也可以工作,但我遇到了一个问题,即它不会将回车符添加到每行(\r),因此在使用脚本后不会发生任何事情
import serial
import time
f = open("Foods.txt", "r")
lines = f.readlines()
for line in lines:
ser = serial.Serial('/dev/cu.SLAB_USBtoUART', 115200, timeout = 1)
commandToSend = lines
ser.write(str(commandToSend).encode()).
所以我进入设备屏幕,按下ender,我得到
["first Line\n", "Second Line\n". "Third Line\n","Fourth Line\n"]
["first Line\n", "Second Line\n". "Third Line\n","Fourth Line\n"]
["first Line\n", "Second Line\n". "Third Line\n","Fourth Line\n"].
["first Line\n", "Second Line\n". "Third Line\n","Fourth Line\n"]
这意味着它会将它们发送到串行控制台,但它没有按“回车”来发送它们,并且在我运行第一个脚本时,它就按了回车键
如何向其添加\r
如果我这样做:
import serial
import time
f = open("Foods.txt", "r")
lines = f.readlines()
for line in lines:
ser = serial.Serial('/dev/cu.SLAB_USBtoUART', 115200, timeout = 1)
commandToSend = lines\r
ser.write(str(commandToSend).encode()).
我明白了
commandToSend = lines\r
^
SyntaxError: unexpected character after line continuation character
第二种方法在我看来是正确的,问题是您正在将
commandToSend
设置为lines
,这是所有行的列表,您想要发送的是line
(您正在循环的列表中的当前行)
因此,您的代码应该是:
导入序列号
导入时间
f=打开(“Foods.txt”、“r”)
行=f.读行()
对于行中的行:
ser=serial.serial('/dev/cu.SLAB_USBtoUART',115200,超时=1)
命令结束=行
ser.write(str(commandToSend.encode())。
此外,如果要添加回车符,则必须将其连接为字符串,例如:
line+'\r'
或
“%s\r%”行
或
'{}\r'.格式(行)
或
f'{line}\r'
取决于首选项/Python版本