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

2024-10-05 15:21:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图修改这个python应用程序{-https://github.com/kliment/Printrun/blob/master/pronsole.py 用于控制3D打印机。基本上,我尝试使用应用程序的命令行版本并添加udp接收,这样我就可以从我制作的iphone应用程序中控制它。我让python应用程序接收udp fine,解密它接收到的不同消息,等等。 这个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)

类中还有另一个名为“dou move”的方法可以移动打印机,当收到udp时,我正在调用该方法。我想我说得对-

^{pr2}$

它试图调用它,但无法调用,因为我还没有连接到打印机。 所以我试着打电话-

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

在类的末尾,但是我得到错误消息-“保存set port失败:pronsole实例没有属性'rc\u 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\u connect方法,但这很有效,所以我不明白为什么不能在python脚本中以同样的方式调用它。我猜这和我引用pronsole的一个实例有关-

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

我试过让它成为一个静态的方法,但是这会产生其他问题。 所以我的问题是,如何从python脚本中调用这个“dounuconnect”方法? 就像我所说的,我是一个python noob;我已经在如何让udp工作和集成方面取得了一些成功,但我还是坚持要做一件事,我觉得这很简单。 任何帮助都将不胜感激。在


Tags: and方法keyinselfcmdlenif
1条回答
网友
1楼 · 发布于 2024-10-05 15:21:08

我最近也想这么做,并通过将python脚本的输出管道到前鞋底.py程序。

因此,我没有修改pronsole代码,而是在另一个python程序中实现了所有的socket功能,并通过stdout将命令发送到pronsole。我的程序名为“pronsole_interface”,因此在命令行中我这样称呼它:

python pronsole_interface.py | pronsole.py

相关问题 更多 >