我已经编写了这个简短的脚本(我已经删除了一些关于大小的小细节),并且我收到了一个非常简单的错误,但是,我不明白为什么!我对 Python 很陌生,所以也许有人可以解释这个问题以及为什么它不起作用?
当我希望将完整的自定义串行写入字符串打印回控制台时,错误似乎发生了,它似乎无法识别我发送到函数的参数。
也许我误解了一些非常简单的事情。即使对 Python 有一点了解,对任何人来说都应该很简单
干杯
代码:
#! /usr/bin/env python
# IMPORTS APPEAR HERE ***
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity='N',
stopbits=1,
bytesize=8
)
# Sets motor number
motor_no = "2"
# Lets create our main GUI class
class ArialApp(object):
# Default init stuff
def __init__(self):
# Create a builder object and create the objects from the .glade file
self.builder = gtk.Builder()
self.builder.add_from_file("../res/main.glade")
self.builder.connect_signals(self)
# Open the serial connection to the encoder and keep it open
ser.open()
# Custom function for sending commands down the serial. Needed to wrap defaults
# arround the custom 'serial.write' command.
self.send_command('A')
# Code removed for space.....
# Custom method for sending commands down serial with default ammendments
def send_command(self, nanotech):
# Send the command with the #, then motor number which should be global, then the command
# sent the the method followed by a return
ser.write("#" + motor_no + nanotech + '\r\n')
# Print to the console the full command sent down the pipe
# [[[ ERROR GOES HERE ]]]
print "#" + motor_no + nanotech + '\r\n'
# Just to show its in here...
if __name__ == "__main__":
app = ArialApp()
gtk.main()
错误:
File "main.py", line 62, in ArialApp
print "#" + motor_no + commands + '\r\n'
NameError: name 'commands' is not defined
最后,简单介绍一下这种情况:
我正在用 Glade 和 Python/PyGTK 编写一个小型 GUI 应用程序,以使用 PySerial 模块通过串行控制步进电机。但是,我想打包我自己的“写入”功能,以便我可以将默认值附加到电缆上的“发送”。例如,电机编号并始终在指令末尾附加回车符。其他诸如在同一函数中立即读回响应之类的事情对于衡量响应也很有用,因此,将其包装到自定义函数中似乎是明智的做法。
任何有关上述问题的建议或帮助,我们将不胜感激。
谢谢您。
安迪
更新:我已经解决了不包含“self”的原始问题,并且我已经设法让 Stack 接受我通常使用的选项卡,因此看起来更干净。还要注意我删除的唯一代码是简单的变量设置。但是,问题仍然存在!
最佳答案
这可能是因为您缺少 self 参数:
def send_command(self, commands):
关于python - Python 中未定义命令 - 真正的基础知识,但令人困惑!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3147786/