嗨,我有以下代码,但不断收到此错误消息:
名称错误:名称“序列”未定义
我已经从许多教程中复制了这段代码,但它不起作用,有人可以告诉我为什么吗?
from serial import*
ser = serial.Serial('/dev/ttyACM0', 9600)
while 1:
ser.readline()
最佳答案
当您以这种方式导入时:
from serial import *
您正在导入内容,就好像它们是在实际文件中声明的一样。来自 Python 文档:
This imports all names except those beginning with an underscore (
_
). Note that in general the practice ofimporting * from
a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.
所以你可以像这样调用Serial
:
ser = Serial('/dev/ttyACM0', 9600)
<小时/>
如果您不想以这种方式导入它(您可能会在覆盖字段或已使用的标识符时遇到问题),您可以使用:
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
关于python - pi 到 arduino 串行通信上的名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21165896/