欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ubuntu下python实现虚拟串口

程序员文章站 2022-05-06 17:49:50
...
#! /usr/bin/env python
#coding=utf-8
import pty
import os
import select

def mkpty():
    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()
    print(master1, master2)
    while True:
        rl, wl, el = select.select([master1,master2], [], [], 1)
        for master in rl:
            print(master)
            data = os.read(master, 128)
            if master==master1:
                os.write(master2, data)
            else:
                os.write(master1, data)