除了Jean-paulcalderone所说的(这基本上是正确的答案),我还使用socat用python编写了以下脚本。在
它可以被导入并实例化到一个解释器中,然后你可以使用它的writeLine方法将数据写入一个(vritual)串行端口,该串行端口通过socat连接到另一个(虚拟)串行端口,另一个twisted应用程序可以在该端口上监听。但正如Jean-paulcalderone所说:如果只是您想要的单元测试,那么您实际上不需要做这些事情。只要看看他提到的那些文件。在import os, subprocess, serial, time
from ConfigParser import SafeConfigParser
class SerialEmulator(object):
def __init__(self,configfile):
config=SafeConfigParser()
config.readfp(open(configfile,'r'))
self.inport=os.path.expanduser(config.get('virtualSerialPorts','inport'))
self.outport=os.path.expanduser(config.get('virtualSerialPorts','outport'))
cmd=['/usr/bin/socat','-d','-d','PTY,link=%s,raw,echo=1'%self.inport,'PTY,link=%s,raw,echo=1'%self.outport]
self.proc=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
time.sleep(3)
self.serial=serial.Serial(self.inport)
self.err=''
self.out=''
def writeLine(self,line):
line=line.strip('\r\n')
self.serial.write('%s\r\n'%line)
def __del__(self):
self.stop()
def stop(self):
self.proc.kill()
self.out,self.err=self.proc.communicate()