如何制作具有 readline 功能的扭曲 python 客户端 [英] How make a twisted python client with readline functionality
问题描述
我正在尝试使用 Python Twisted 为简单的 TCP 服务器编写客户端.当然,我对 Python 还很陌生,刚刚开始研究 Twisted,所以我可能做错了.
I'm trying to write a client for simple TCP server using Python Twisted. Of course I pretty new to Python and just started looking at Twisted so I could be doing it all wrong.
服务器很简单,您打算使用 nc 或 telnet.没有身份验证.您只需连接并获得一个简单的控制台.我想编写一个添加一些 readline 功能的客户端(历史和 emacs 像 ctrl-a/ctrl-e 是我所追求的)
The server is simple and you're intended to use use nc or telnet. There is no authentication. You just connect and get a simple console. I'd like to write a client that adds some readline functionality (history and emacs like ctrl-a/ctrl-e are what I'm after)
下面是我写的代码,它的效果和在命令行中使用 netcat 一样好 nc localhost 4118
Below is code I've written that works just as good as using netcat from the command line like this nc localhost 4118
from twisted.internet import reactor, protocol, stdio
from twisted.protocols import basic
from sys import stdout
host='localhost'
port=4118
console_delimiter='\n'
class MyConsoleClient(protocol.Protocol):
def dataReceived(self, data):
stdout.write(data)
stdout.flush()
def sendData(self,data):
self.transport.write(data+console_delimiter)
class MyConsoleClientFactory(protocol.ClientFactory):
def startedConnecting(self,connector):
print 'Starting connection to console.'
def buildProtocol(self, addr):
print 'Connected to console!'
self.client = MyConsoleClient()
self.client.name = 'console'
return self.client
def clientConnectionFailed(self, connector, reason):
print 'Connection failed with reason:', reason
class Console(basic.LineReceiver):
factory = None
delimiter = console_delimiter
def __init__(self,factory):
self.factory = factory
def lineReceived(self,line):
if line == 'quit':
self.quit()
else:
self.factory.client.sendData(line)
def quit(self):
reactor.stop()
def main():
factory = MyConsoleClientFactory()
stdio.StandardIO(Console(factory))
reactor.connectTCP(host,port,factory)
reactor.run()
if __name__ == '__main__':
main()
输出:
$ python ./console-console-client.py
Starting connection to console.
Connected to console!
console> version
d305dfcd8fc23dc6674a1d18567a3b4e8383d70e
console> number-events
338
console> quit
我看过
这真的不适合我.示例代码效果很好,但是当我介绍网络时,我似乎与 stdio 存在竞争条件.这个较旧的链接似乎提倡一种类似的方法(在单独的线程中运行 readline),但我并没有得到它.
This really didn't work out for me. The example code works great but when I introduced networking I seemed to have race conditions with stdio. This older link seems to advocate a similar approach (running readline in a seperate thread) but I didn't get far with it.
我还研究了扭曲的海螺侮辱,但除了演示示例之外,我没有任何运气得到任何工作.
I've also looked into twisted conch insults but I haven't had any luck getting anything to work other than the demo examples.
制作可提供 readline 支持的基于终端的客户端的最佳方法是什么?
What's the best way to make a terminal based client that would provide readline support?
http://twistedmatrix.com/documents/current/api/twisted.conch.stdio.html
看起来很有希望,但我很困惑如何使用它.
looks promising but I'm confused how to use it.
http://twistedmatrix.com/documents/current/api/twisted.conch.recvline.HistoricRecvLine.html
例如,似乎也提供了处理向上和向下箭头的支持,但我无法切换控制台以从 HistoricRecVLine 继承而不是 LineReceiver 来运行.
also seems to provide support for handling up and down arrow for instance but I couldn't get switching Console to inherit from HistoricRecVLine instead of LineReceiver to function.
也许twisted 是使用错误的框架,或者我应该使用所有的海螺类.我只是喜欢它的事件驱动风格.是否有更好/更简单的方法来在扭曲的客户端中获得 readline 或 readline 之类的支持?
Maybe twisted is the wrong framework to be using or I should be using all conch classes. I just liked the event driven style of it. Is there a better/easier approach to having readline or readline like support in a twisted client?
推荐答案
我通过不使用 Twisted 框架解决了这个问题.这是一个很棒的框架,但我认为它是完成这项工作的错误工具.相反,我使用了 telnetlib
、cmd
和 readline
模块.
I landed up solving this by not using the Twisted framework. It's a great framework but I think it was the wrong tool for the job. Instead I used the telnetlib
, cmd
and readline
modules.
我的服务器是异步的,但这并不意味着我的客户端需要异步,所以我使用 telnetlib
与服务器进行通信.这使得创建 ConsoleClient
类变得容易,该类继承了 cmd.Cmd
并获取历史记录和类似 emacs 的快捷方式.
My server is asynchronous but that didn't mean my client needed to be so I used telnetlib
for my communication to the server. This made it easy to create a ConsoleClient
class which subclasses cmd.Cmd
and get history and emacs-like shortcuts.
#! /usr/bin/env python
import telnetlib
import readline
import os
import sys
import atexit
import cmd
import string
HOST='127.0.0.1'
PORT='4118'
CONSOLE_PROMPT='console> '
class ConsoleClient(cmd.Cmd):
"""Simple Console Client in Python. This allows for readline functionality."""
def connect_to_console(self):
"""Can throw an IOError if telnet connection fails."""
self.console = telnetlib.Telnet(HOST,PORT)
sys.stdout.write(self.read_from_console())
sys.stdout.flush()
def read_from_console(self):
"""Read from console until prompt is found (no more data to read)
Will throw EOFError if the console is closed.
"""
read_data = self.console.read_until(CONSOLE_PROMPT)
return self.strip_console_prompt(read_data)
def strip_console_prompt(self,data_received):
"""Strip out the console prompt if present"""
if data_received.startswith(CONSOLE_PROMPT):
return data_received.partition(CONSOLE_PROMPT)[2]
else:
#The banner case when you first connect
if data_received.endswith(CONSOLE_PROMPT):
return data_received.partition(CONSOLE_PROMPT)[0]
else:
return data_received
def run_console_command(self,line):
self.write_to_console(line + '\n')
data_recved = self.read_from_console()
sys.stdout.write(self.strip_console_prompt(data_recved))
sys.stdout.flush()
def write_to_console(self,line):
"""Write data to the console"""
self.console.write(line)
sys.stdout.flush()
def do_EOF(self, line):
try:
self.console.write("quit\n")
self.console.close()
except IOError:
pass
return True
def do_help(self,line):
"""The server already has it's own help command. Use that"""
self.run_console_command("help\n")
def do_quit(self, line):
return self.do_EOF(line)
def default(self, line):
"""Allow a command to be sent to the console."""
self.run_console_command(line)
def emptyline(self):
"""Don't send anything to console on empty line."""
pass
def main():
histfile = os.path.join(os.environ['HOME'], '.consolehistory')
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
try:
console_client = ConsoleClient()
console_client.prompt = CONSOLE_PROMPT
console_client.connect_to_console()
doQuit = False;
while doQuit != True:
try:
console_client.cmdloop()
doQuit = True;
except KeyboardInterrupt:
#Allow for ^C (Ctrl-c)
sys.stdout.write('\n')
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except EOFError:
pass
if __name__ == '__main__':
main()
我所做的一项更改是删除从服务器返回的提示,并使用 Cmd.prompt
向用户显示.我的理由是支持 Ctrl-c 更像一个 shell.
One change I did was remove the prompt returned from the server and use Cmd.prompt
to display to the user. I reason was to support Ctrl-c acting more like a shell.
这篇关于如何制作具有 readline 功能的扭曲 python 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!