pty模块是一个虚拟终端库。也可以虚拟出一个串口。
在嵌入式开发过程中,你一定有这样一种需求:想在虚拟机上调试串口的通信。
那么这个pty库是可以满足你的需求的。
#coding=utf-8
import pty
import os
import select
def mkpty():
#Open a new tty
master1, slave = pty.openpty()
slaveName1 = os.ttyname(slave)
master2, slave = pty.openpty()
slaveName2 = os.ttyname(slave)
print ('\nslave device names:', slaveName1, slaveName2)
return master1, master2
if __name__ == "__main__":
master1, master2 = mkpty()
while True:
# rl=read list, wait until ready to reading
# wl=write list, wait until ready to writing
# el=exception list, wait for an "exceptional condition"
# timeout = 1s
rl, wl, el = select.select([master1, master2], [], [], None)
for device in rl:
data = os.read(device, 128)
if device == master1:
print("read from master1: %s" % (len(data), data))
os.write(master2, data)
else:
os.write(master1, data)