I am trying to test out a virtual serial connection in python with individual funtions for each test.
'''
Testing Virtual Serial Port Connections
'''
import os
import sys
import time
import serial
DATA = b'Hello\\n'
class TestSerial():
"""Test PTY serial open"""
def setUp(self):
# Open PTY
self.master, self.slave = os.openpty()
self.s_name = os.ttyname(self.slave)
self.ser = serial.Serial(self.s_name, timeout=1)
def openPtySlave(self):
with serial.Serial(os.ttyname(self.slave), timeout=1) as slave:
pass # OK
def testPtyWrite(self):
fd = os.fdopen(self.master,'wb')
fd.write(DATA)
fd.flush()
out = self.ser.read(len(DATA))
print(out)
def testPtyRead(self):
fd = open(self.master, 'rb')
self.ser.write(DATA)
self.ser.flush()
out = fd.read(len(DATA))
print(out)
if __name__ == '__main__':
sys.stdout.write(__doc__)
PtyTest = TestSerial()
PtyTest.setUp()
PtyTest.openPtySlave()
PtyTest.testPtyWrite()
PtyTest.testPtyRead()
But every time I execute the code I get the following error:
Traceback (most recent call last):
File "/Main/pty.py", line 48, in \<module\>
PtyTest.testPtyRead()
File "/Main/pty.py", line 35, in testPtyRead
fd = open(self.master, 'rb')
OSError: \[Errno 9\] Bad file descriptor
The script opens the file to write to it but fails in the read function.
I've tried closing the file in the write function before exiting but I still get the error.
Can anyone help?