如何在Python脚本中调用此方法?

2 投票
1 回答
745 浏览
提问于 2025-04-17 20:06

我正在尝试修改一个用Python写的应用程序,这个程序是用来控制3D打印机的。简单来说,我想把这个应用的命令行版本加上UDP接收功能,这样我就可以通过我自己做的iPhone应用来控制它。我已经让这个Python应用能够接收UDP信号,并且能够理解它收到的不同消息。

这个Python脚本里有一个类,里面定义了所有使用的方法。下面是一个非常简化的版本,包含了我遇到问题的方法-

class pronsole(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        if not READLINE:
            self.completekey = None
        self.p = printcore.printcore()
        self.p.recvcb = self.recvcb
        self.recvlisteners = []
        self.prompt = "PC>"
        self.p.onlinecb = self.online
        self.f = None
    ...

    def do_connect(self, l):
        a = l.split()
        p = self.scanserial()
        port = self.settings.port
        if (port == "" or port not in p) and len(p)>0:
            port = p[0]
        baud = self.settings.baudrate or 115200
        if(len(a)>0):
            port = a[0]
        if(len(a)>1):
            try:
                baud = int(a[1])
            except:
                print "Bad baud value '"+a[1]+"' ignored"
        if len(p) == 0 and not port:
            print "No serial ports detected - please specify a port"
            return
        if len(a) == 0:
            print "No port specified - connecting to %s at %dbps" % (port, baud)
        if port != self.settings.port:
            self.settings.port = port
            self.save_in_rc("set port", "set port %s" % port)
        if baud != self.settings.baudrate:
            self.settings.baudrate = baud
            self.save_in_rc("set baudrate", "set baudrate %d" % baud)
        self.p.connect(port, baud)

这个类里还有一个叫做'do_move'的方法,它是用来移动打印机的。我在接收到UDP信号时调用这个方法。我觉得我调用得没错-

a = pronsole()
a.do_move("X 29")

它试图调用这个方法,但因为我还没有连接到打印机,所以无法执行。我尝试在类的末尾调用-

a = pronsole()
a.do_connect("")

但我得到了一个错误信息:“保存失败,设置端口:pronsole实例没有属性'rc_filename'”。

试图使用'rc_filename'的方法是这个-

def save_in_rc(self, key, definition):
    """
    Saves or updates macro or other definitions in .pronsolerc
    key is prefix that determines what is being defined/updated (e.g. 'macro foo')
    definition is the full definition (that is written to file). (e.g. 'macro foo move x 10')
    Set key as empty string to just add (and not overwrite)
    Set definition as empty string to remove it from .pronsolerc
    To delete line from .pronsolerc, set key as the line contents, and definition as empty string
    Only first definition with given key is overwritten.
    Updates are made in the same file position.
    Additions are made to the end of the file.
    """
    rci, rco = None, None
    if definition != "" and not definition.endswith("\n"):
        definition += "\n"
    try:
        written = False
        if os.path.exists(self.rc_filename):
            import shutil
            shutil.copy(self.rc_filename, self.rc_filename+"~bak")
            rci = codecs.open(self.rc_filename+"~bak", "r", "utf-8")
        rco = codecs.open(self.rc_filename, "w", "utf-8")
        if rci is not None:
            overwriting = False
            for rc_cmd in rci:
                l = rc_cmd.rstrip()
                ls = l.lstrip()
                ws = l[:len(l)-len(ls)] # just leading whitespace
                if overwriting and len(ws) == 0:
                    overwriting = False
                if not written and key != "" and  rc_cmd.startswith(key) and (rc_cmd+"\n")[len(key)].isspace():
                    overwriting = True
                    written = True
                    rco.write(definition)
                if not overwriting:
                    rco.write(rc_cmd)
                    if not rc_cmd.endswith("\n"): rco.write("\n")
        if not written:
            rco.write(definition)
        if rci is not None:
            rci.close()
        rco.close()
        #if definition != "":
        #    print "Saved '"+key+"' to '"+self.rc_filename+"'"
        #else:
        #    print "Removed '"+key+"' from '"+self.rc_filename+"'"
    except Exception, e:
        print "Saving failed for", key+":", str(e)
    finally:
        del rci, rco

我尝试通过命令行调用do_connect方法,这个方法可以正常工作,所以我不明白为什么在Python脚本中不能以同样的方式调用它。我猜这可能和我在调用时引用了pronsole的一个实例有关-

a = pronsole()
a.do_connect("")

我尝试把它做成一个静态方法,但这又引发了其他问题。所以我的问题是,我该如何在Python脚本中调用这个'do_connect'方法?就像我说的,我是个Python新手;我在让UDP工作和集成方面取得了一些不错的进展,但在这个我觉得很简单的事情上卡住了。任何帮助都会非常感激。

1 个回答

1

我最近也想做这个,最后通过把一个python脚本的输出传给pronsole.py程序解决了这个问题。

所以,我没有去修改pronsole的代码,而是把所有的socket功能都写在了另一个python程序里,然后通过标准输出把命令发送给pronsole。我的程序叫做'pronsole_interface',所以在命令行里我这样调用它:

python pronsole_interface.py | pronsole.py

撰写回答