pySerial can be used with Python’s with
statement like this:
JavaScript
x
4
1
with serial.Serial("/dev/ttyS1") as ser:
2
ser.write("AAAA")
3
ser.read(8)
4
I tried to see exactly what it is pySerial does to make this work, but I couldn’t find an __enter__
or __exit__
function anywhere! I ran grep -e '(__enter__)|(__exit__)' *.py
from the pySerial directory, and grep didn’t find either function. How does pySerial do it?
Edit: I also tried the following to see what was called next:
JavaScript
1
4
1
import serial, pdb
2
with serial.Serial("/dev/ttyUSB0") as ser:
3
pdb.set_trace()
4
This brought me directly to line 433 of serialposix.py
, the close()
function. Does the with
statement also look for open()
and close()
functions?
Advertisement
Answer
Serial
class doesn’t implement these methods, it inherits them from io.IOBase
. The relevant part from /serial/serialposix.py:
JavaScript
1
11
11
1
try:
2
import io
3
except ImportError:
4
# classic version with our own file-like emulation
5
class Serial(PosixSerial, FileLike):
6
pass
7
else:
8
# io library present
9
class Serial(PosixSerial, io.RawIOBase):
10
pass
11