Tools¶
This module can be executed to get a list of ports ( python -m serial.tools.list_ports ). It also contains the following functions.
serial.tools.list_ports.comports()¶
Returns: | an iterable that yields ListPortInfo objects. |
---|
The function returns an iterable that yields tuples of three strings:
- port name as it can be passed to serial.Serial or serial.serial_for_url()
- description in human readable form
- sort of hardware ID. E.g. may contain VID:PID of USB-serial adapters.
Items are returned in no particular order. It may make sense to sort the items. Also note that the reported strings are different across platforms and operating systems, even for the same device.
Support is limited to a number of operating systems. On some systems description and hardware ID will not be available ( None ).
Platform: | Posix (/dev files) |
---|---|
Platform: | Linux (/dev files, sysfs and lsusb) |
Platform: | OSX (iokit) |
Platform: | Windows (setupapi, registry) |
serial.tools.list_ports.grep(regexp)¶
Parameters: | regexp – regular expression (see stdlib re ) |
---|---|
Returns: | an iterable that yields ListPortInfo objects, see also comports() . |
Search for ports using a regular expression. Port name, description and hardware ID are searched (case insensitive). The function returns an iterable that contains the same tuples that comport() generates, but includes only those entries that match the regexp.
This object holds information about a serial port. It supports indexed access for backwards compatibility, as in port, desc, hwid = info .
Full device name/path, e.g. /dev/ttyUSB0 . This is also the information returned as first element when accessed by index.
Short device name, e.g. ttyUSB0 .
Human readable description or n/a . This is also the information returned as second element when accessed by index.
Technical description or n/a . This is also the information returned as third element when accessed by index.
USB specific data, these are all None if it is not a USB device (or the platform does not support extended info).
USB Vendor ID (integer, 0. 65535).
USB product ID (integer, 0. 65535).
USB serial number as a string.
USB manufacturer string, as reported by device.
USB product string, as reported by device.
Interface specifc description, e.g. used in compound USB devices.
Comparison operators are implemented such that the ListPortInfo objects can be sorted by device . Strings are split into groups of numbers and text so that the order is “natural” (i.e. com1 < com2 < com10 ).
Command line usage
Help for python -m serial.tools.list_ports :
usage: list_ports.py [-h] [-v] [-q] [-n N] [regexp] Serial port enumeration positional arguments: regexp only show ports that match this regex optional arguments: -h, --help show this help message and exit -v, --verbose show more messages -q, --quiet suppress all messages -n N only output the N-th entry
- List all ports with details:
$ python -m serial.tools.list_ports -v /dev/ttyS0 desc: ttyS0 hwid: PNP0501 /dev/ttyUSB0 desc: CP2102 USB to UART Bridge Controller hwid: USB VID:PID=10C4:EA60 SER=0001 LOCATION=2-1.6 2 ports found
$ python -m serial.tools.list_ports 1234:5678 -q -n 2 /dev/ttyUSB1
Changed in version 3.0: returning ListPortInfo objects instead of a tuple
serial.tools.miniterm¶
This is a console application that provides a small terminal application. Miniterm itself does not implement any terminal features such as VT102 compatibility. However it may inherit these features from the terminal it is run. For example on GNU/Linux running from an xterm it will support the escape sequences of the xterm. On Windows the typical console window is dumb and does not support any escapes. When ANSI.sys is loaded it supports some escapes.
--- Miniterm on /dev/ttyS0: 9600,8,N,1 --- --- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
Command line options can be given so that binary data including escapes for terminals are escaped or output as hex.
Miniterm supports RFC 2217 remote serial ports and raw sockets using URL Handlers such as rfc2217:://: respectively socket://: as port argument when invoking.
Command line options python -m serial.tools.miniterm -h :
usage: miniterm.py [-h] [--parity ] [--rtscts] [--xonxoff] [--rts RTS] [--dtr DTR] [-e] [--encoding CODEC] [-f NAME] [--eol ] [--raw] [--exit-char NUM] [--menu-char NUM] [-q] [--develop] [port] [baudrate] Miniterm - A simple terminal program for the serial port. positional arguments: port serial port name baudrate set baud rate, default: 9600 optional arguments: -h, --help show this help message and exit port settings: --parity set parity, one of , default: N --rtscts enable RTS/CTS flow control (default off) --xonxoff enable software flow control (default off) --rts RTS set initial RTS line state (possible values: 0, 1) --dtr DTR set initial DTR line state (possible values: 0, 1) --ask ask again for port when open fails data handling: -e, --echo enable local echo (default off) --encoding CODEC set the encoding for the serial port (e.g. hexlify, Latin1, UTF-8), default: UTF-8 -f NAME, --filter NAME add text transformation --eol end of line mode --raw Do no apply any encodings/transformations hotkeys: --exit-char NUM Unicode of special character that is used to exit the application, default: 29 --menu-char NUM Unicode code of special character that is used to control miniterm (menu), default: 20 diagnostics: -q, --quiet suppress non-error messages --develop show Python traceback on error
Miniterm supports some control functions. Typing Ctrl+T Ctrl+H when it is running shows the help text:
--- pySerial (3.0a) - miniterm - help --- --- Ctrl+] Exit program --- Ctrl+T Menu escape key, followed by: --- Menu keys: --- Ctrl+T Send the menu character itself to remote --- Ctrl+] Send the exit character itself to remote --- Ctrl+I Show info --- Ctrl+U Upload file (prompt will be shown) --- Ctrl+A encoding --- Ctrl+F edit filters --- Toggles: --- Ctrl+R RTS Ctrl+D DTR Ctrl+B BREAK --- Ctrl+E echo Ctrl+L EOL --- --- Port settings (Ctrl+T followed by the following): --- p change port --- 7 8 set data bits --- N E O S M change parity (None, Even, Odd, Space, Mark) --- 1 2 3 set stop bits (1, 2, 1.5) --- b change baud rate --- x X disable/enable software flow control --- r R disable/enable hardware flow control
Changed in version 2.5: Added Ctrl+T menu and added support for opening URLs.
Changed in version 2.6: File moved from the examples to serial.tools.miniterm .
Changed in version 3.0: Apply encoding on serial port, convert to Unicode for console. Added new filters, default to stripping terminal control sequences. Added –ask option.
Short introduction¶
Open port at “38400,8,E,1”, non blocking HW handshaking:
>>> ser = serial.Serial('COM3', 38400, timeout=0, . parity=serial.PARITY_EVEN, rtscts=1) >>> s = ser.read(100) # read up to one hundred bytes . # or as much is in the buffer
Configuring ports later¶
Get a Serial instance and configure/open it later:
>>> ser = serial.Serial() >>> ser.baudrate = 19200 >>> ser.port = 'COM1' >>> ser Serial(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0) >>> ser.open() >>> ser.is_open True >>> ser.close() >>> ser.is_open False
with serial.Serial() as ser: ser.baudrate = 19200 ser.port = 'COM1' ser.open() ser.write(b'hello')
Readline¶
readline() reads up to one line, including the \n at the end. Be careful when using readline() . Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. If the \n is missing in the return value, it returned on timeout.
readlines() tries to read “all” lines which is not well defined for a serial port that is still open. Therefore readlines() depends on having a timeout on the port and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly. The returned list of lines do not include the \n .
Both functions call read() to get their data and the serial port timeout is acting on this function. Therefore the effective timeout, especially for readlines() , can be much larger.
Do also have a look at the example files in the examples directory in the source distribution or online.
The eol parameter for readline() is no longer supported when pySerial is run with newer Python versions (V2.6+) where the module io is available.
EOL¶
To specify the EOL character for readline() or to use universal newline mode, it is advised to use io.TextIOWrapper:
import serial import io ser = serial.serial_for_url('loop://', timeout=1) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) sio.write(unicode("hello\n")) sio.flush() # it is buffering. required to get the data out *now* hello = sio.readline() print(hello == unicode("hello\n"))
Testing ports¶
Listing ports¶
python -m serial.tools.list_ports will print a list of available ports. It is also possible to add a regexp as first argument and the list will only include entries that matched.
The enumeration may not work on all operating systems. It may be incomplete, list unavailable ports or may lack detailed descriptions of the ports.
Accessing ports¶
pySerial includes a small console based terminal program called serial.tools.miniterm . It can be started with python -m serial.tools.miniterm (use option -h to get a listing of all options).
© Copyright 2001-2020, Chris Liechti Revision 31fa4807 .
Versions latest stable Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.
Short introduction¶
Open port at “38400,8,E,1”, non blocking HW handshaking:
>>> ser = serial.Serial('COM3', 38400, timeout=0, . parity=serial.PARITY_EVEN, rtscts=1) >>> s = ser.read(100) # read up to one hundred bytes . # or as much is in the buffer
Configuring ports later¶
Get a Serial instance and configure/open it later:
>>> ser = serial.Serial() >>> ser.baudrate = 19200 >>> ser.port = 'COM1' >>> ser Serial(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0) >>> ser.open() >>> ser.is_open True >>> ser.close() >>> ser.is_open False
with serial.Serial() as ser: ser.baudrate = 19200 ser.port = 'COM1' ser.open() ser.write(b'hello')
Readline¶
Be careful when using readline() . Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.
Do also have a look at the example files in the examples directory in the source distribution or online.
The eol parameter for readline() is no longer supported when pySerial is run with newer Python versions (V2.6+) where the module io is available.
EOL¶
To specify the EOL character for readline() or to use universal newline mode, it is advised to use io.TextIOWrapper:
import serial import io ser = serial.serial_for_url('loop://', timeout=1) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) sio.write(unicode("hello\n")) sio.flush() # it is buffering. required to get the data out *now* hello = sio.readline() print(hello == unicode("hello\n"))
Testing ports¶
Listing ports¶
python -m serial.tools.list_ports will print a list of available ports. It is also possible to add a regexp as first argument and the list will only include entries that matched.
The enumeration may not work on all operating systems. It may be incomplete, list unavailable ports or may lack detailed descriptions of the ports.
Accessing ports¶
pySerial includes a small console based terminal program called serial.tools.miniterm . It can be started with python -m serial.tools.miniterm (use option -h to get a listing of all options).
© Copyright 2001-2020, Chris Liechti Revision 0e763474 .
Versions latest stable Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.