Skip to main content
 首页 » 编程设计

python之命令未在 Python 中定义之真正的基础知识,但很困惑!

2024年08月12日30rubylouvre

我写了这个简短的脚本(我已经删除了一些次要的细节)并且我遇到了一个非常简单的错误,但是我不明白为什么!我是 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):