如何将 raw_input 与twisted 一起使用?
我知道 raw_input 不能在扭曲中使用。然而,这是我想要的应用程序。
我有一个提供交互式终端串行端口的硬件。我正在尝试连接到此端口并以异步方式发送命令。我需要这种方式,因为这是一个电机控制器,一旦我发出命令,它就会“阻止”并逃跑(我当前的代码)。我需要能够输入另一个命令,例如 ESTOP,以防出现问题或危险。
我读过一些关于 twisted.internet.stdio.StandardIO 的内容,但是我没有太多运气。 对此的任何建议/帮助都会很棒。
I am aware that raw_input cannot be used in twisted. However here is my desired application.
I have an piece of hardware that provides an interactive terminal serial port. I am trying to connect to this port and send commands in an async manner. I need it this way because this is a motor controller that once I issue a command it will "block" and run away (my current code). I need to be able to enter another command such as ESTOP in case of problems or danger.
I have read some stuff about twisted.internet.stdio.StandardIO
however I have not had much luck..
Any advice / help on this would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有几个选项可供您使用。一种是使用子进程来处理与串行端口的通信,并使用管道在父进程和子进程之间进行通信(这通过 Twisted 的进程协议进行了简化)。另一种方法是分离一个单独的 Python 线程并从那里使用 raw_input 。正常的线程间通信机制可以在 Twisted 中正常工作。唯一真正的扭曲来自于如何从单独的线程中唤醒扭曲的反应堆。主要支持的机制是使用
reactor.callFromThread()< /代码>
。在 Twisted 中使用线程需要仔细考虑,并且很容易搞砸(这就是为什么它通常不被鼓励),但有时它确实是完成这项工作的正确工具。
You have a couple of options here that you can use. One would be to use a child process to handle communicating with the serial port and a pipe to communicate between the parent and child (which is simplified by Twisted's Process Protocol). Another is to spin off a separate Python thread and use raw_input from there. Normal inter-thread communication mechanisms work fine with Twisted. The only real twist comes from how you wake the twisted reactor from the separate thread. The primary supported mechanism for this is using
reactor.callFromThread()
. Use of threads in Twisted requires some careful thought and is easy to screw up (which is why it's generally discouraged) but occasionally it really is the right tool for the job.您看过 StandardIO 示例吗? Twisted 核心示例中有几个,stdin.py 和 stdiodemo.py。有一个更高级的示例 涉及 Twisted Conch 中的线路编辑和历史记录。您可以使用 python -mtwisted.conch.stdio 运行此命令以查看其实际效果。 Conch 示例可能仅适用于 POSIX 平台,不适用于 Windows。
Have you seen the StandardIO examples? There are a couple in the Twisted core examples, stdin.py and stdiodemo.py. There is a more advanced example that involves line editing and history in Twisted Conch. You can run this one with
python -m twisted.conch.stdio
to see it in action. The Conch example probably only works on POSIX platforms, not Windows.