I am aware that raw_input cannot be used in twisted. However here is my desired application.
I have an piece of hardware th开发者_如何转开发at 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.
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.
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.
精彩评论