python打开伪终端_如何使用python中的伪终端来模拟串行端口?

除了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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值