How to use / dev / ptmx to create a virtual serial port?

I have a program using pyserial and I want to test it without using a real serial port device.

On Windows, I use com0com, and on linux, I know that there is a way to create a virtual serial port pair without using an additional program.

so I'm looking for guidance and found pts, / dev / ptmx, but I don’t know how to create a pair by following the guidelines, can anyone give me an example?

I tried (in python):

f = open("/dev/ptmx", "r")

and it works, / dev / pts / 4 is created.

and I tried:

f = open("/dev/4", "w")

and the result:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 5] Input/output error: '/dev/pts/4'

edit: I found a solution (workround) using socat.

socat PTY,link=COM8 PTY,link=COM9

then COM8 COM9 are created as a pair of virtual serial ports.

+5
5

Per , ptsname, , , ,

slave, grantpt (3) unlockpt (3).

ctypes .

+2

, TCP/Serial... , . :

import os, pty, serial

master, slave = pty.openpty()
s_name = os.ttyname(slave)

ser = serial.Serial(s_name)

# To Write to the device
ser.write('Your text')

# To read from the device
os.read(master,1000)

, (/dev/ptmx), fd , , , , . , - , , .

+4

python, : C. man /dev/ptmx. , !. linuxquestions , C.

, , , .

0

pty, . ( /dev/ptmx openpty , .)

0

You can create a dummy object that implements the same interface as the classes pySerialyou use, but do something completely different and easily copied, for example, reading and writing to files / terminal, etc.

For example:

class DummySerial():
  #you should consider subclassing this
  def __init__(self, *args, **kwargs):
    self.fIn = open("input.raw", 'r')
    self.fOut = open("output.raw", 'w')
    pass
  def read(self, bytes = 1):
    return self.fIn.read(bytes)
  def write(self, data):
    self.fOut.write(data)
  def close(self):
    self.fIn.close()
    self.fOut.close()
  #implement more methods here

If he is stunned like a duck, and he ducks like a duck ...

0
source

All Articles