ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## Installation[](http://pythonhosted.org/pyserial/pyserial.html#installation "Permalink to this headline") ### pyserial[](http://pythonhosted.org/pyserial/pyserial.html#id1 "Permalink to this headline") This installs a package that can be used from Python (import serial). To install for all users on the system, administrator rights (root) may be required. #### From PyPI[](http://pythonhosted.org/pyserial/pyserial.html#from-pypi "Permalink to this headline") pySerial can be installed from PyPI, either manually downloading the files and installing as described below or using: pip install pyserial or: easy_install -U pyserial #### From source (tar.gz or checkout)[](http://pythonhosted.org/pyserial/pyserial.html#from-source-tar-gz-or-checkout "Permalink to this headline") Download the archive from [http://pypi.python.org/pypi/pyserial](http://pypi.python.org/pypi/pyserial). Unpack the archive, enter the pyserial-x.y directory and run: python setup.py install For Python 3.x: python3 setup.py install # Short introduction[](http://pythonhosted.org/pyserial/shortintro.html#short-introduction "Permalink to this headline") ## Opening serial ports[](http://pythonhosted.org/pyserial/shortintro.html#opening-serial-ports "Permalink to this headline") Open port at “9600,8,N,1”, no timeout: >>> import serial >>> ser = serial.Serial('/dev/ttyUSB0') # open serial port >>> print(ser.name) # check which port was really used >>> ser.write(b'hello') # write a string >>> ser.close() # close port Open named port at “19200,8,N,1”, 1s timeout: >>> with serial.Serial('/dev/ttyS1', 19200, timeout=1) as ser: ... x = ser.read() # read one byte ... s = ser.read(10) # read up to ten bytes (timeout) ... line = ser.readline() # read a '\n' terminated line 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[](http://pythonhosted.org/pyserial/shortintro.html#configuring-ports-later "Permalink to this headline") 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 Also supported with context manager: serial.Serial() as ser: ser.baudrate = 19200 ser.port = 'COM1' ser.open() ser.write(b'hello') ## Readline[](http://pythonhosted.org/pyserial/shortintro.html#readline "Permalink to this headline") Be carefully 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. Note The eol parameter for readline() is no longer supported when pySerial is run with newer Python versions (V2.6+) where the module [io](http://docs.python.org/library/io.html#module-io "(in Python v2.7)") is available. ### EOL[](http://pythonhosted.org/pyserial/shortintro.html#eol "Permalink to this headline") To specify the EOL character for readline() or to use universal newline mode, it is advised to use [io.TextIOWrapper](http://docs.python.org/library/io.html#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[](http://pythonhosted.org/pyserial/shortintro.html#testing-ports "Permalink to this headline") ### Listing ports[](http://pythonhosted.org/pyserial/shortintro.html#listing-ports "Permalink to this headline") 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. Note 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[](http://pythonhosted.org/pyserial/shortintro.html#accessing-ports "Permalink to this headline") pySerial includes a small console based terminal program called [*serial.tools.miniterm*](http://pythonhosted.org/pyserial/tools.html#miniterm). It ca be started with python -m serial.tools.miniterm  (use option -h to get a listing of all options). # pySerial API[](http://pythonhosted.org/pyserial/pyserial_api.html#module-serial "Permalink to this headline") ## Classes[](http://pythonhosted.org/pyserial/pyserial_api.html#classes "Permalink to this headline") ### Native ports[](http://pythonhosted.org/pyserial/pyserial_api.html#native-ports "Permalink to this headline") *class *serial.Serial[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "Permalink to this definition") __init__(*port=None*, *baudrate=9600*, *bytesize=EIGHTBITS*, *parity=PARITY_NONE*, *stopbits=STOPBITS_ONE*, *timeout=None*, *xonxoff=False*, *rtscts=False*, *write_timeout=None*, *dsrdtr=False*, *inter_byte_timeout=None*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.__init__ "Permalink to this definition") | Parameters: | * **port** – Device name or None. * **baudrate** ([*int*](http://docs.python.org/library/functions.html#int "(in Python v2.7)")) – Baud rate such as 9600 or 115200 etc. * **bytesize** – Number of data bits. Possible values: [FIVEBITS](http://pythonhosted.org/pyserial/pyserial_api.html#serial.FIVEBITS "serial.FIVEBITS"), [SIXBITS](http://pythonhosted.org/pyserial/pyserial_api.html#serial.SIXBITS "serial.SIXBITS"), [SEVENBITS](http://pythonhosted.org/pyserial/pyserial_api.html#serial.SEVENBITS "serial.SEVENBITS"), [EIGHTBITS](http://pythonhosted.org/pyserial/pyserial_api.html#serial.EIGHTBITS "serial.EIGHTBITS") * **parity** – Enable parity checking. Possible values: [PARITY_NONE](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_NONE "serial.PARITY_NONE"), [PARITY_EVEN](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_EVEN "serial.PARITY_EVEN"), [PARITY_ODD](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_ODD "serial.PARITY_ODD") [PARITY_MARK](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_MARK "serial.PARITY_MARK"), [PARITY_SPACE](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_SPACE "serial.PARITY_SPACE") * **stopbits** – Number of stop bits. Possible values: [STOPBITS_ONE](http://pythonhosted.org/pyserial/pyserial_api.html#serial.STOPBITS_ONE "serial.STOPBITS_ONE"), [STOPBITS_ONE_POINT_FIVE](http://pythonhosted.org/pyserial/pyserial_api.html#serial.STOPBITS_ONE_POINT_FIVE "serial.STOPBITS_ONE_POINT_FIVE"), [STOPBITS_TWO](http://pythonhosted.org/pyserial/pyserial_api.html#serial.STOPBITS_TWO "serial.STOPBITS_TWO") * **timeout** ([*float*](http://docs.python.org/library/functions.html#float "(in Python v2.7)")) – Set a read timeout value. * **xonxoff** ([*bool*](http://docs.python.org/library/functions.html#bool "(in Python v2.7)")) – Enable software flow control. * **rtscts** ([*bool*](http://docs.python.org/library/functions.html#bool "(in Python v2.7)")) – Enable hardware (RTS/CTS) flow control. * **dsrdtr** ([*bool*](http://docs.python.org/library/functions.html#bool "(in Python v2.7)")) – Enable hardware (DSR/DTR) flow control. * **write_timeout** ([*float*](http://docs.python.org/library/functions.html#float "(in Python v2.7)")) – Set a write timeout value. * **inter_byte_timeout** ([*float*](http://docs.python.org/library/functions.html#float "(in Python v2.7)")) – Inter-character timeout, None to disable (default). | | Raises: | * **ValueError** – Will be raised when parameter are out of range, e.g. baud rate, data bits. * **SerialException** – In case the device can not be found or can not be configured. | The port is immediately opened on object creation, when a *port* is given. It is not opened when *port* is None and a successive call to [open()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.open "serial.Serial.open") is required. *port* is a device name: depending on operating system. e.g. /dev/ttyUSB0 on GNU/Linux or COM3 on Windows. The parameter *baudrate* can be one of the standard values: 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200\. These are well supported on all platforms. Standard values above 115200, such as: 230400, 460800, 500000, 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000, 3000000, 3500000, 4000000 also work on many platforms and devices. Non-standard values are also supported on some platforms (GNU/Linux, MAC OSX >= Tiger, Windows). Though, even on these platforms some serial ports may reject non-standard values. Possible values for the parameter *timeout* which controls the behavior of [read()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.read "serial.Serial.read"): * timeout = None: wait forever / until requested number of bytes are received * timeout = 0: non-blocking mode, return immediately in any case, returning zero or more, up to the requested number of bytes * timeout = x: set timeout to x seconds (float allowed) returns immediately when the requested number of bytes are available, otherwise wait until the timeout expires and return all bytes that were received until then. [write()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.write "serial.Serial.write") is blocking by default, unless *write_timeout* is set. For possible values refer to the list for *timeout* above. Note that enabling both flow control methods (*xonxoff* and *rtscts*) together may not be supported. It is common to use one of the methods at once, not both. *dsrdtr* is not supported by all platforms (silently ignored). Setting it to None has the effect that its state follows *rtscts*. Also consider using the function [serial_for_url()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.serial_for_url "serial.serial_for_url") instead of creating Serial instances directly. Changed in version 2.5: *dsrdtr* now defaults to False (instead of *None*) Changed in version 3.0: numbers as *port* argument are no longer supported open()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.open "Permalink to this definition") Open port. close()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.close "Permalink to this definition") Close port immediately. __del__()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.__del__ "Permalink to this definition") Destructor, close port when serial port instance is freed. The following methods may raise [SerialException](http://pythonhosted.org/pyserial/pyserial_api.html#serial.SerialException "serial.SerialException") when applied to a closed port. read(*size=1*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.read "Permalink to this definition") | Parameters: | **size** – Number of bytes to read. | | Returns: | Bytes read from the port. | | Return type: | bytes | Read *size* bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read. Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and [str](http://docs.python.org/library/functions.html#str "(in Python v2.7)") otherwise. write(*data*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.write "Permalink to this definition") | Parameters: | **data** – Data to send. | | Returns: | Number of bytes written. | | Return type: | int | | Raises SerialTimeoutException: | |   | In case a write timeout is configured for the port and the time is exceeded. | Write the bytes *data* to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8'). Changed in version 2.5: Accepts instances of bytes and [bytearray](http://docs.python.org/library/functions.html#bytearray "(in Python v2.7)") when available (Python 2.6 and newer) and [str](http://docs.python.org/library/functions.html#str "(in Python v2.7)") otherwise. Changed in version 2.5: Write returned None in previous versions. flush()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.flush "Permalink to this definition") Flush of file like objects. In this case, wait until all data is written. in_waiting[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.in_waiting "Permalink to this definition") | Getter: | Get the number of bytes in the input buffer | | Type: | int | Return the number of bytes in the receive buffer. Changed in version 3.0: changed to property from inWaiting() out_waiting[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.out_waiting "Permalink to this definition") | Getter: | Get the number of bytes in the output buffer | | Type: | int | | Platform: | Posix | | Platform: | Windows | Return the number of bytes in the output buffer. Changed in version 2.7: (Posix support added) Changed in version 3.0: changed to property from outWaiting() reset_input_buffer()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.reset_input_buffer "Permalink to this definition") Flush input buffer, discarding all it’s contents. Changed in version 3.0: renamed from flushInput() reset_output_buffer()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.reset_output_buffer "Permalink to this definition") Clear output buffer, aborting the current output and discarding all that is in the buffer. Changed in version 3.0: renamed from flushOutput() send_break(*duration=0.25*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.send_break "Permalink to this definition") | Parameters: | **duration** ([*float*](http://docs.python.org/library/functions.html#float "(in Python v2.7)")) – Time to activate the BREAK condition. | Send break condition. Timed, returns to idle state after given duration. break_condition[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.break_condition "Permalink to this definition") | Getter: | Get the current BREAK state | | Setter: | Control the BREAK state | | Type: | bool | When set to True activate BREAK condition, else disable. Controls TXD. When active, no transmitting is possible. rts[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.rts "Permalink to this definition") | Setter: | Set the state of the RTS line | | Getter: | Return the state of the RTS line | | Type: | bool | Set RTS line to specified logic level. It is possible to assign this value before opening the serial port, then the value is applied uppon [open()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.open "serial.Serial.open"). dtr[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.dtr "Permalink to this definition") | Setter: | Set the state of the DTR line | | Getter: | Return the state of the DTR line | | Type: | bool | Set DTR line to specified logic level. It is possible to assign this value before opening the serial port, then the value is applied uppon [open()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.open "serial.Serial.open"). Read-only attributes: name[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.name "Permalink to this definition") | Getter: | Device name. | | Type: | str | New in version 2.5. cts[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.cts "Permalink to this definition") | Getter: | Get the state of the CTS line | | Type: | bool | Return the state of the CTS line. dsr[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.dsr "Permalink to this definition") | Getter: | Get the state of the DSR line | | Type: | bool | Return the state of the DSR line. ri[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.ri "Permalink to this definition") | Getter: | Get the state of the RI line | | Type: | bool | Return the state of the RI line. cd[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.cd "Permalink to this definition") | Getter: | Get the state of the CD line | | Type: | bool | Return the state of the CD line New values can be assigned to the following attributes (properties), the port will be reconfigured, even if it’s opened at that time: port[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.port "Permalink to this definition") | Type: | str | Read or write port. When the port is already open, it will be closed and reopened with the new setting. baudrate[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.baudrate "Permalink to this definition") | Getter: | Get current baud rate | | Setter: | Set new baud rate | | Type: | int | Read or write current baud rate setting. bytesize[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.bytesize "Permalink to this definition") | Getter: | Get current byte size | | Setter: | Set new byte size. Possible values: [FIVEBITS](http://pythonhosted.org/pyserial/pyserial_api.html#serial.FIVEBITS "serial.FIVEBITS"), [SIXBITS](http://pythonhosted.org/pyserial/pyserial_api.html#serial.SIXBITS "serial.SIXBITS"), [SEVENBITS](http://pythonhosted.org/pyserial/pyserial_api.html#serial.SEVENBITS "serial.SEVENBITS"), [EIGHTBITS](http://pythonhosted.org/pyserial/pyserial_api.html#serial.EIGHTBITS "serial.EIGHTBITS") | | Type: | int | Read or write current data byte size setting. parity[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.parity "Permalink to this definition") | Getter: | Get current parity setting | | Setter: | Set new parity mode. Possible values: [PARITY_NONE](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_NONE "serial.PARITY_NONE"), [PARITY_EVEN](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_EVEN "serial.PARITY_EVEN"), [PARITY_ODD](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_ODD "serial.PARITY_ODD") [PARITY_MARK](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_MARK "serial.PARITY_MARK"), [PARITY_SPACE](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_SPACE "serial.PARITY_SPACE") | Read or write current parity setting. stopbits[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.stopbits "Permalink to this definition") | Getter: | Get current stop bit setting | | Setter: | Set new stop bit setting. Possible values: [STOPBITS_ONE](http://pythonhosted.org/pyserial/pyserial_api.html#serial.STOPBITS_ONE "serial.STOPBITS_ONE"), [STOPBITS_ONE_POINT_FIVE](http://pythonhosted.org/pyserial/pyserial_api.html#serial.STOPBITS_ONE_POINT_FIVE "serial.STOPBITS_ONE_POINT_FIVE"), [STOPBITS_TWO](http://pythonhosted.org/pyserial/pyserial_api.html#serial.STOPBITS_TWO "serial.STOPBITS_TWO") | Read or write current stop bit width setting. timeout[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.timeout "Permalink to this definition") | Getter: | Get current read timeout setting | | Setter: | Set read timeout | | Type: | float (seconds) | Read or write current read timeout setting. write_timeout[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.write_timeout "Permalink to this definition") | Getter: | Get current write timeout setting | | Setter: | Set write timeout | | Type: | float (seconds) | Read or write current write timeout setting. Changed in version 3.0: renamed from writeTimeout inter_byte_timeout[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.inter_byte_timeout "Permalink to this definition") | Getter: | Get current inter byte timeout setting | | Setter: | Disable (None) or enable the inter byte timeout | | Type: | float or None | Read or write current inter byte timeout setting. Changed in version 3.0: renamed from interCharTimeout xonxoff[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.xonxoff "Permalink to this definition") | Getter: | Get current software flow control setting | | Setter: | Enable or disable software flow control | | Type: | bool | Read or write current software flow control rate setting. rtscts[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.rtscts "Permalink to this definition") | Getter: | Get current hardware flow control setting | | Setter: | Enable or disable hardware flow control | | Type: | bool | Read or write current hardware flow control setting. dsrdtr[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.dsrdtr "Permalink to this definition") | Getter: | Get current hardware flow control setting | | Setter: | Enable or disable hardware flow control | | Type: | bool | Read or write current hardware flow control setting. rs485_mode[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.rs485_mode "Permalink to this definition") | Getter: | Get the current RS485 settings | | Setter: | Disable (None) or enable the RS485 settings | | Type: | [rs485.RS485Settings](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings "serial.rs485.RS485Settings") or None | | Platform: | Posix (Linux, limited set of hardware) | | Platform: | Windows (only RTS on TX possible) | Attribute to configure RS485 support. When set to an instance of [rs485.RS485Settings](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings "serial.rs485.RS485Settings") and supported by OS, RTS will be active when data is sent and inactive otherwise (for reception). The [rs485.RS485Settings](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings "serial.rs485.RS485Settings") class provides additional settings supported on some platforms. New in version 3.0. The following constants are also provided: BAUDRATES[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.BAUDRATES "Permalink to this definition") A list of valid baud rates. The list may be incomplete, such that higher and/or intermediate baud rates may also be supported by the device (Read Only). BYTESIZES[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.BYTESIZES "Permalink to this definition") A list of valid byte sizes for the device (Read Only). PARITIES[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.PARITIES "Permalink to this definition") A list of valid parities for the device (Read Only). STOPBITS[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.STOPBITS "Permalink to this definition") A list of valid stop bit widths for the device (Read Only). The following methods are for compatibility with the [io](http://docs.python.org/library/io.html#module-io "(in Python v2.7)") library. readable()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.readable "Permalink to this definition") | Returns: | True | New in version 2.5. writable()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.writable "Permalink to this definition") | Returns: | True | New in version 2.5. seekable()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.seekable "Permalink to this definition") | Returns: | False | New in version 2.5. readinto(*b*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.readinto "Permalink to this definition") | Parameters: | **b** – bytearray or array instance | | Returns: | Number of byte read | Read up to len(b) bytes into [bytearray](http://docs.python.org/library/functions.html#bytearray "(in Python v2.7)") *b* and return the number of bytes read. New in version 2.5. The port settings can be read and written as dictionary. The following keys are supported: write_timeout, inter_byte_timeout, dsrdtr, baudrate, timeout, parity, bytesize, rtscts, stopbits, xonxoff get_settings()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.get_settings "Permalink to this definition") | Returns: | a dictionary with current port settings. | | Return type: | dict | Get a dictionary with port settings. This is useful to backup the current settings so that a later point in time they can be restored using [apply_settings()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.apply_settings "serial.Serial.apply_settings"). Note that control lines (RTS/DTR) are part of the settings. New in version 2.5. Changed in version 3.0: renamed from getSettingsDict apply_settings(*d*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.apply_settings "Permalink to this definition") | Parameters: | **d** ([*dict*](http://docs.python.org/library/stdtypes.html#dict "(in Python v2.7)")) – a dictionary with port settings. | Applies a dictionary that was created by [get_settings()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.get_settings "serial.Serial.get_settings"). Only changes are applied and when a key is missing, it means that the setting stays unchanged. Note that control lines (RTS/DTR) are not changed. New in version 2.5. Changed in version 3.0: renamed from applySettingsDict Platform specific methods. Warning Programs using the following methods and attributes are not portable to other platforms! nonblocking()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.nonblocking "Permalink to this definition") | Platform: | Posix | Configure the device for nonblocking operation. This can be useful if the port is used with [select](http://docs.python.org/library/select.html#module-select "(in Python v2.7)"). Note that [timeout](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.timeout "serial.Serial.timeout") must also be set to 0 fileno()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.fileno "Permalink to this definition") | Platform: | Posix | | Returns: | File descriptor. | Return file descriptor number for the port that is opened by this object. It is useful when serial ports are used with [select](http://docs.python.org/library/select.html#module-select "(in Python v2.7)"). set_input_flow_control(*enable*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.set_input_flow_control "Permalink to this definition") | Platform: | Posix | | Parameters: | **enable** ([*bool*](http://docs.python.org/library/functions.html#bool "(in Python v2.7)")) – Set flow control state. | Manually control flow - when software flow control is enabled. This will send XON (true) and XOFF (false) to the other device. New in version 2.7: (Posix support added) Changed in version 3.0: renamed from flowControlOut set_output_flow_control(*enable*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.set_output_flow_control "Permalink to this definition") | Platform: | Posix (HW and SW flow control) | | Platform: | Windows (SW flow control only) | | Parameters: | **enable** ([*bool*](http://docs.python.org/library/functions.html#bool "(in Python v2.7)")) – Set flow control state. | Manually control flow of outgoing data - when hardware or software flow control is enabled. Sending will be suspended when called with False and enabled when called with True. Changed in version 2.7: (renamed on Posix, function was called flowControl) Changed in version 3.0: renamed from setXON Note The following members are deprecated and will be removed in a future release. portstr[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.portstr "Permalink to this definition") Deprecated since version 2.5: use [name](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.name "serial.Serial.name") instead inWaiting()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.inWaiting "Permalink to this definition") Deprecated since version 3.0: see [in_waiting](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.in_waiting "serial.Serial.in_waiting") writeTimeout[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.writeTimeout "Permalink to this definition") Deprecated since version 3.0: see [write_timeout](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.write_timeout "serial.Serial.write_timeout") interCharTimeout[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.interCharTimeout "Permalink to this definition") Deprecated since version 3.0: see [inter_byte_timeout](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.inter_byte_timeout "serial.Serial.inter_byte_timeout") sendBreak(*duration=0.25*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.sendBreak "Permalink to this definition") Deprecated since version 3.0: see [send_break()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.send_break "serial.Serial.send_break") flushInput()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.flushInput "Permalink to this definition") Deprecated since version 3.0: see [reset_input_buffer()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.reset_input_buffer "serial.Serial.reset_input_buffer") flushOutput()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.flushOutput "Permalink to this definition") Deprecated since version 3.0: see [reset_output_buffer()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.reset_output_buffer "serial.Serial.reset_output_buffer") setBreak(*level=True*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.setBreak "Permalink to this definition") Deprecated since version 3.0: see [break_condition](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.break_condition "serial.Serial.break_condition") setRTS(*level=True*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.setRTS "Permalink to this definition") Deprecated since version 3.0: see [rts](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.rts "serial.Serial.rts") setDTR(*level=True*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.setDTR "Permalink to this definition") Deprecated since version 3.0: see [dtr](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.dtr "serial.Serial.dtr") getCTS()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.getCTS "Permalink to this definition") Deprecated since version 3.0: see [cts](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.cts "serial.Serial.cts") getDSR()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.getDSR "Permalink to this definition") Deprecated since version 3.0: see [dsr](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.dsr "serial.Serial.dsr") getRI()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.getRI "Permalink to this definition") Deprecated since version 3.0: see [ri](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.ri "serial.Serial.ri") getCD()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.getCD "Permalink to this definition") Deprecated since version 3.0: see [cd](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.cd "serial.Serial.cd") getSettingsDict()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.getSettingsDict "Permalink to this definition") Deprecated since version 3.0: see [get_settings()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.get_settings "serial.Serial.get_settings") applySettingsDict(*d*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.applySettingsDict "Permalink to this definition") Deprecated since version 3.0: see [apply_settings()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.apply_settings "serial.Serial.apply_settings") outWaiting()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.outWaiting "Permalink to this definition") Deprecated since version 3.0: see [out_waiting](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.out_waiting "serial.Serial.out_waiting") setXON(*level=True*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.setXON "Permalink to this definition") Deprecated since version 3.0: see [set_output_flow_control()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.set_output_flow_control "serial.Serial.set_output_flow_control") flowControlOut(*enable*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.flowControlOut "Permalink to this definition") Deprecated since version 3.0: see [set_input_flow_control()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.set_input_flow_control "serial.Serial.set_input_flow_control") rtsToggle[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.rtsToggle "Permalink to this definition") | Platform: | Windows | Attribute to configure RTS toggle control setting. When enabled and supported by OS, RTS will be active when data is available and inactive if no data is available. New in version 2.6. Changed in version 3.0: (removed, see [rs485_mode](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.rs485_mode "serial.Serial.rs485_mode") instead) Implementation detail: some attributes and functions are provided by the class SerialBase and some by the platform specific class and others by the base class mentioned above. ### RS485 support[](http://pythonhosted.org/pyserial/pyserial_api.html#rs485-support "Permalink to this headline") The [Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "serial.Serial") class has a [Serial.rs485_mode](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.rs485_mode "serial.Serial.rs485_mode") attribute which allows to enable RS485 specific support on some platforms. Currently Windows and Linux (only a small number of devices) are supported. [Serial.rs485_mode](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.rs485_mode "serial.Serial.rs485_mode") needs to be set to an instance of [rs485.RS485Settings](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings "serial.rs485.RS485Settings") to enable or to None to disable this feature. Usage: ser = serial.Serial(...) ser.rs485_mode = serial.rs485.RS485Settings(...) ser.write(b'hello') There is a subclass [rs485.RS485](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485 "serial.rs485.RS485") available to emulate the RS485 support on regular serial ports. *class *rs485.RS485Settings[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings "Permalink to this definition") A class that holds RS485 specific settings which are supported on some platforms. New in version 3.0. __init__(rts_level_for_tx=True, rts_level_for_rx=False, loopback=False, delay_before_tx=None, delay_before_rx=None): | Parameters: | * **rts_level_for_tx** ([*bool*](http://docs.python.org/library/functions.html#bool "(in Python v2.7)")) – RTS level for transmission * **rts_level_for_rx** ([*bool*](http://docs.python.org/library/functions.html#bool "(in Python v2.7)")) – RTS level for reception * **loopback** ([*bool*](http://docs.python.org/library/functions.html#bool "(in Python v2.7)")) – When set to True transmitted data is also received. * **delay_before_tx** ([*float*](http://docs.python.org/library/functions.html#float "(in Python v2.7)")) – Delay after setting RTS but before transmission starts * **delay_before_rx** ([*float*](http://docs.python.org/library/functions.html#float "(in Python v2.7)")) – Delay after transmission ends and resetting RTS | rts_level_for_tx[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings.rts_level_for_tx "Permalink to this definition") RTS level for transmission. rts_level_for_rx[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings.rts_level_for_rx "Permalink to this definition") RTS level for reception. loopback[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings.loopback "Permalink to this definition") When set to True transmitted data is also received. delay_before_tx[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings.delay_before_tx "Permalink to this definition") Delay after setting RTS but before transmission starts (seconds as float). delay_before_rx[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485Settings.delay_before_rx "Permalink to this definition") Delay after transmission ends and resetting RTS (seconds as float). *class *rs485.RS485[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rs485.RS485 "Permalink to this definition") A subclass that replaces the [Serial.write()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.write "serial.Serial.write") method with one that toggles RTS according to the RS485 settings. Usage: ser = serial.rs485.RS485(...) ser.rs485_mode = serial.rs485.RS485Settings(...) ser.write(b'hello') Warning This may work unreliably on some serial ports (control signals not synchronized or delayed compared to data). Using delays may be unreliable (varying times, larger than expected) as the OS may not support very fine grained delays (no smaller than in the order of tens of milliseconds). Note Some implementations support this natively in the class [Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "serial.Serial"). Better performance can be expected when the native version is used. Note The loopback property is ignored by this implementation. The actual behavior depends on the used hardware. ### [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) Network ports[](http://pythonhosted.org/pyserial/pyserial_api.html#rfc-2217-network-ports "Permalink to this headline") Warning This implementation is currently in an experimental state. Use at your own risk. *class *rfc2217.Serial[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rfc2217.Serial "Permalink to this definition") This implements a [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) compatible client. Port names are [*URL*](http://pythonhosted.org/pyserial/url_handlers.html#urls) in the form: rfc2217://:[?[&]] This class API is compatible to [Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "serial.Serial") with a few exceptions: * write_timeout is not implemented * The current implementation starts a thread that keeps reading from the (internal) socket. The thread is managed automatically by the [rfc2217.Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rfc2217.Serial "serial.rfc2217.Serial") port object on open()/close(). However it may be a problem for user applications that like to use select instead of threads. Due to the nature of the network and protocol involved there are a few extra points to keep in mind: * All operations have an additional latency time. * Setting control lines (RTS/CTS) needs more time. * Reading the status lines (DSR/DTR etc.) returns a cached value. When that cache is updated depends entirely on the server. The server itself may implement a polling at a certain rate and quick changes may be invisible. * The network layer also has buffers. This means that flush(), reset_input_buffer() and reset_output_buffer() may work with additional delay. Likewise in_waiting returns the size of the data arrived at the objects internal buffer and excludes any bytes in the network buffers or any server side buffer. * Closing and immediately reopening the same port may fail due to time needed by the server to get ready again. Not implemented yet / Possible problems with the implementation: * [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) flow control between client and server (objects internal buffer may eat all your memory when never read). * No authentication support (servers may not prompt for a password etc.) * No encryption. Due to lack of authentication and encryption it is not suitable to use this client for connections across the internet and should only be used in controlled environments. New in version 2.5. *class *rfc2217.PortManager[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rfc2217.PortManager "Permalink to this definition") This class provides helper functions for implementing [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) compatible servers. Basically, it implements everything needed for the [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) protocol. It just does not open sockets and read/write to serial ports (though it changes other port settings). The user of this class must take care of the data transmission itself. The reason for that is, that this way, this class supports all programming models such as threads and select. Usage examples can be found in the examples where two TCP/IP - serial converters are shown, one using threads (the single port server) and an other using select (the multi port server). Note Each new client connection must create a new instance as this object (and the [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) protocol) has internal state. __init__(*serial_port*, *connection*, *debug_output=False*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rfc2217.PortManager.__init__ "Permalink to this definition") | Parameters: | * **serial_port** – a [Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "serial.Serial") instance that is managed. * **connection** – an object implementing write(), used to write to the network. * **debug_output** – enables debug messages: a [logging.Logger](http://docs.python.org/library/logging.html#logging.Logger "(in Python v2.7)") instance or None. | Initializes the Manager and starts negotiating with client in Telnet and [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) protocol. The negotiation starts immediately so that the class should be instantiated in the moment the client connects. The *serial_port* can be controlled by [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) commands. This object will modify the port settings (baud rate etc.) and control lines (RTS/DTR) send BREAK etc. when the corresponding commands are found by the [filter()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rfc2217.PortManager.filter "serial.rfc2217.PortManager.filter") method. The *connection* object must implement a write() function. This function must ensure that *data* is written at once (no user data mixed in, i.e. it must be thread-safe). All data must be sent in its raw form ([escape()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rfc2217.PortManager.escape "serial.rfc2217.PortManager.escape") must not be used) as it is used to send Telnet and [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) control commands. For diagnostics of the connection or the implementation, *debug_output* can be set to an instance of a [logging.Logger](http://docs.python.org/library/logging.html#logging.Logger "(in Python v2.7)") (e.g. logging.getLogger('rfc2217.server')). The caller should configure the logger using setLevel for the desired detail level of the logs. escape(*data*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rfc2217.PortManager.escape "Permalink to this definition") | Parameters: | **data** – data to be sent over the network. | | Returns: | data, escaped for Telnet/[**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) | A generator that escapes all data to be compatible with [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html). Implementors of servers should use this function to process all data sent over the network. The function returns a generator which can be used in for loops. It can be converted to bytes using [serial.to_bytes()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.to_bytes "serial.to_bytes"). filter(*data*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rfc2217.PortManager.filter "Permalink to this definition") | Parameters: | **data** – data read from the network, including Telnet and [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) controls. | | Returns: | data, free from Telnet and [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) controls. | A generator that filters and processes all data related to [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html). Implementors of servers should use this function to process all data received from the network. The function returns a generator which can be used in for loops. It can be converted to bytes using [serial.to_bytes()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.to_bytes "serial.to_bytes"). check_modem_lines(*force_notification=False*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.rfc2217.PortManager.check_modem_lines "Permalink to this definition") | Parameters: | **force_notification** – Set to false. Parameter is for internal use. | This function needs to be called periodically (e.g. every second) when the server wants to send NOTIFY_MODEMSTATE messages. This is required to support the client for reading CTS/DSR/RI/CD status lines. The function reads the status line and issues the notifications automatically. New in version 2.5. See also [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) - Telnet Com Port Control Option ## Exceptions[](http://pythonhosted.org/pyserial/pyserial_api.html#exceptions "Permalink to this headline") *exception *serial.SerialException[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.SerialException "Permalink to this definition") Base class for serial port exceptions. Changed in version 2.5: Now derives from IOError instead of Exception *exception *serial.SerialTimeoutException[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.SerialTimeoutException "Permalink to this definition") Exception that is raised on write timeouts. ## Constants[](http://pythonhosted.org/pyserial/pyserial_api.html#constants "Permalink to this headline") *Parity* serial.PARITY_NONE[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_NONE "Permalink to this definition") serial.PARITY_EVEN[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_EVEN "Permalink to this definition") serial.PARITY_ODD[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_ODD "Permalink to this definition") serial.PARITY_MARK[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_MARK "Permalink to this definition") serial.PARITY_SPACE[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.PARITY_SPACE "Permalink to this definition") *Stop bits* serial.STOPBITS_ONE[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.STOPBITS_ONE "Permalink to this definition") serial.STOPBITS_ONE_POINT_FIVE[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.STOPBITS_ONE_POINT_FIVE "Permalink to this definition") serial.STOPBITS_TWO[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.STOPBITS_TWO "Permalink to this definition") Note that 1.5 stop bits are not supported on POSIX. It will fall back to 2 stop bits. *Byte size* serial.FIVEBITS[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.FIVEBITS "Permalink to this definition") serial.SIXBITS[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.SIXBITS "Permalink to this definition") serial.SEVENBITS[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.SEVENBITS "Permalink to this definition") serial.EIGHTBITS[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.EIGHTBITS "Permalink to this definition") *Others* Default control characters (instances of bytes for Python 3.0+) for software flow control: serial.XON[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.XON "Permalink to this definition") serial.XOFF[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.XOFF "Permalink to this definition") Module version: serial.VERSION[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.VERSION "Permalink to this definition") A string indicating the pySerial version, such as 3.0. New in version 2.3. ## Module functions and attributes[](http://pythonhosted.org/pyserial/pyserial_api.html#module-functions-and-attributes "Permalink to this headline") serial.device(*number*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.device "Permalink to this definition") Changed in version 3.0: removed, use serial.tools.list_ports instead serial.serial_for_url(*url*, **args*, ***kwargs*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.serial_for_url "Permalink to this definition") | Parameters: | * **url** – Device name, number or [*URL*](http://pythonhosted.org/pyserial/url_handlers.html#urls) * **do_not_open** – When set to true, the serial port is not opened. | | Returns: | an instance of [Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "serial.Serial") or a compatible object. | Get a native or a [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) implementation of the Serial class, depending on port/url. This factory function is useful when an application wants to support both, local ports and remote ports. There is also support for other types, see [*URL*](http://pythonhosted.org/pyserial/url_handlers.html#urls) section. The port is not opened when a keyword parameter called *do_not_open* is given and true, by default it is opened. New in version 2.5. serial.protocol_handler_packages[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.protocol_handler_packages "Permalink to this definition") This attribute is a list of package names (strings) that is searched for protocol handlers. e.g. we want to support a URL foobar://. A module my_handlers.protocol_foobar is provided by the user: serial.protocol_handler_packages.append("my_handlers") s = serial.serial_for_url("foobar://") For an URL starting with XY:// is the function [serial_for_url()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.serial_for_url "serial.serial_for_url") attempts to import PACKAGE.protocol_XY with each candidate for PACKAGE from this list. New in version 2.6. serial.to_bytes(*sequence*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.to_bytes "Permalink to this definition") | Parameters: | **sequence** – bytes, bytearray or memoryview | | Returns: | an instance of bytes | Convert a sequence to a bytes type. This is used to write code that is compatible to Python 2.x and 3.x. In Python versions prior 3.x, bytes is a subclass of str. They convert str([17]) to '[17]' instead of '\x11' so a simple bytes(sequence) doesn’t work for all versions of Python. This function is used internally and in the unit tests. New in version 2.5. serial.iterbytes(*sequence*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.iterbytes "Permalink to this definition") | Parameters: | **sequence** – bytes, bytearray or memoryview | | Returns: | a generator that yields bytes | Some versions of Python (3.x) would return integers instead of bytes when looping over an instance of bytes. This helper function ensures that bytes are returned. New in version 3.0. ## Threading[](http://pythonhosted.org/pyserial/pyserial_api.html#module-serial.threaded "Permalink to this headline") New in version 3.0. Warning This implementation is currently in an experimental state. Use at your own risk. This module provides classes to simplify working with threads and protocols. *class *serial.threaded.Protocol[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Protocol "Permalink to this definition") Protocol as used by the [ReaderThread](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread "serial.threaded.ReaderThread"). This base class provides empty implementations of all methods. connection_made(*transport*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Protocol.connection_made "Permalink to this definition") | Parameters: | **transport** – instance used to write to serial port. | Called when reader thread is started. data_received(*data*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Protocol.data_received "Permalink to this definition") | Parameters: | **data** (*bytes*) – received bytes | Called with snippets received from the serial port. connection_lost(*exc*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Protocol.connection_lost "Permalink to this definition") | Parameters: | **exc** – Exception if connection was terminated by error else None | Called when the serial port is closed or the reader loop terminated otherwise. *class *serial.threaded.Packetizer(*Protocol*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Packetizer "Permalink to this definition") Read binary packets from serial port. Packets are expected to be terminated with a TERMINATOR byte (null byte by default). The class also keeps track of the transport. TERMINATOR = b'\0' __init__()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Packetizer.__init__ "Permalink to this definition") connection_made(*transport*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Packetizer.connection_made "Permalink to this definition") Stores transport. connection_lost(*exc*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Packetizer.connection_lost "Permalink to this definition") Forgets transport. data_received(*data*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Packetizer.data_received "Permalink to this definition") | Parameters: | **data** (*bytes*) – partial received data | Buffer received data and search for TERMINATOR, when found, call [handle_packet()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Packetizer.handle_packet "serial.threaded.Packetizer.handle_packet"). handle_packet(*packet*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Packetizer.handle_packet "Permalink to this definition") Process packets - to be overridden by subclassing. *class *serial.threaded.LineReader(*Packetizer*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.LineReader "Permalink to this definition") Read and write (Unicode) lines from/to serial port. The encoding is applied. TERMINATOR = b'\r\n' ENCODING = 'utf-8' UNICODE_HANDLING = 'replace' handle_packet(*packet*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.LineReader.handle_packet "Permalink to this definition") handle_line(*line*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.LineReader.handle_line "Permalink to this definition") | Parameters: | **line** ([*str*](http://docs.python.org/library/functions.html#str "(in Python v2.7)")) – Unicode string with one line (excluding line terminator) | Process one line - to be overridden by subclassing. write_line(*text*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.LineReader.write_line "Permalink to this definition") | Parameters: | **text** ([*str*](http://docs.python.org/library/functions.html#str "(in Python v2.7)")) – Unicode string with one line (excluding line terminator) | Write *text* to the transport. *text* is expected to be a Unicode string and the encoding is applied before sending and also the TERMINATOR (new line) is appended. *class *serial.threaded.ReaderThread(*threading.Thread*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread "Permalink to this definition") Implement a serial port read loop and dispatch to a Protocol instance (like the asyncio.Protocol) but do it with threads. Calls to [close()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.close "serial.threaded.ReaderThread.close") will close the serial port but it is also possible to just [stop()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.stop "serial.threaded.ReaderThread.stop") this thread and continue to use the serial port instance otherwise. __init__(*serial_instance*, *protocol_factory*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.__init__ "Permalink to this definition") | Parameters: | * **serial_instance** – serial port instance (opened) to be used. * **protocol_factory** – a callable that returns a Protocol instance | Initialize thread. Note that the serial_instance ‘s timeout is set to one second! Other settings are not changed. stop()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.stop "Permalink to this definition") Stop the reader thread. run()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.run "Permalink to this definition") The actual reader loop driven by the thread. It calls [Protocol.connection_made()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Protocol.connection_made "serial.threaded.Protocol.connection_made"), reads from the serial port calling [Protocol.data_received()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Protocol.data_received "serial.threaded.Protocol.data_received") and finally calls [Protocol.connection_lost()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.Protocol.connection_lost "serial.threaded.Protocol.connection_lost") when [close()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.close "serial.threaded.ReaderThread.close") is called or an error occurs. write(*data*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.write "Permalink to this definition") | Parameters: | **data** (*bytes*) – data to write | Thread safe writing (uses lock). close()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.close "Permalink to this definition") Close the serial port and exit reader thread, calls [stop()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.stop "serial.threaded.ReaderThread.stop") (uses lock). connect()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.connect "Permalink to this definition") Wait until connection is set up and return the transport and protocol instances. This class can be used as context manager, in this case it starts the thread and connects automatically. The serial port is closed when the context is left. __enter__()[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.__enter__ "Permalink to this definition") | Returns: | protocol | Connect and return protocol instance. __exit__(*exc_type*, *exc_val*, *exc_tb*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.threaded.ReaderThread.__exit__ "Permalink to this definition") Closes serial port. Example: class PrintLines(LineReader): def connection_made(self, transport): super(PrintLines, self).connection_made(transport) sys.stdout.write('port opened\n') self.write_line('hello world') def handle_line(self, data): sys.stdout.write('line received: {}\n'.format(repr(data))) def connection_lost(self, exc): if exc: traceback.print_exc(exc) sys.stdout.write('port closed\n') ser = serial.serial_for_url('loop://', baudrate=115200, timeout=1) with ReaderThread(ser, PrintLines) as protocol: protocol.write_line('hello') time.sleep(2) ## asyncio[](http://pythonhosted.org/pyserial/pyserial_api.html#module-serial.aio "Permalink to this headline") Warning This implementation is currently in an experimental state. Use at your own risk. Experimental asyncio support is available for Python 3.4 and newer. The module [serial.aio](http://pythonhosted.org/pyserial/pyserial_api.html#module-serial.aio "serial.aio") provides a asyncio.Transport: SerialTransport. A factory function (asyncio.coroutine) is provided: serial.aio.create_serial_connection(*loop*, *protocol_factory*, **args*, ***kwargs*)[](http://pythonhosted.org/pyserial/pyserial_api.html#serial.aio.create_serial_connection "Permalink to this definition") | Parameters: | * **loop** – The event handler * **protocol_factory** – Factory function for a asyncio.Protocol * **args** – Passed to the [serial.Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "serial.Serial") init function * **kwargs** – Passed to the [serial.Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "serial.Serial") init function | | Platform: | Posix | Get a connection making coroutine. Example: class Output(asyncio.Protocol): def connection_made(self, transport): self.transport = transport print('port opened', transport) transport.serial.rts = False transport.write(b'hello world\n') def data_received(self, data): print('data received', repr(data)) self.transport.close() def connection_lost(self, exc): print('port closed') asyncio.get_event_loop().stop() loop = asyncio.get_event_loop() coro = serial.aio.create_serial_connection(loop, Output, '/dev/ttyUSB0', baudrate=115200) loop.run_until_complete(coro) loop.run_forever() loop.close() # Tools[](http://pythonhosted.org/pyserial/tools.html#module-serial "Permalink to this headline") ## serial.tools.list_ports[](http://pythonhosted.org/pyserial/tools.html#module-serial.tools.list_ports "Permalink to this headline") 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()[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.comports "Permalink to this definition") | Returns: | an iterable that yields [ListPortInfo](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo "serial.tools.list_ports.ListPortInfo") objects. | The function returns an iterable that yields tuples of three strings: * port name as it can be passed to [serial.Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "serial.Serial") or [serial.serial_for_url()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.serial_for_url "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. Note 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*)[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.grep "Permalink to this definition") | Parameters: | **regexp** – regular expression (see stdlib [re](http://docs.python.org/library/re.html#module-re "(in Python v2.7)")) | | Returns: | an iterable that yields [ListPortInfo](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo "serial.tools.list_ports.ListPortInfo") objects, see also [comports()](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.comports "serial.tools.list_ports.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. *class *serial.tools.list_ports.ListPortInfo[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo "Permalink to this definition") This object holds information about a serial port. It supports indexed access for backwards compatibility, as in port, desc, hwid = info. device[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.device "Permalink to this definition") Full device name/path, e.g. /dev/ttyUSB0. This is also the information returned as first element when accessed by index. name[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.name "Permalink to this definition") Short device name, e.g. ttyUSB0. description[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.description "Permalink to this definition") Human readable description or n/a. This is also the information returned as second element when accessed by index. hwid[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.hwid "Permalink to this definition") 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). vid[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.vid "Permalink to this definition") USB Vendor ID (integer, 0...65535). pid[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.pid "Permalink to this definition") USB product ID (integer, 0...65535). serial_number[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.serial_number "Permalink to this definition") USB serial number as a string. location[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.location "Permalink to this definition") USB device location string (“-[-]...”) manufacturer[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.manufacturer "Permalink to this definition") USB manufacturer string, as reported by device. product[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.product "Permalink to this definition") USB product string, as reported by device. interface[](http://pythonhosted.org/pyserial/tools.html#serial.tools.list_ports.ListPortInfo.interface "Permalink to this definition") 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 Examples: * 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 * List the 2nd port matching a USB VID:PID pattern: $ python -m serial.tools.list_ports 1234:5678 -q -n 2 /dev/ttyUSB1 New in version 2.6. Changed in version 3.0: returning ListPortInfo objects instead of a tuple ## serial.tools.miniterm[](http://pythonhosted.org/pyserial/tools.html#module-serial.tools.miniterm "Permalink to this headline") 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: --- 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**](http://tools.ietf.org/html/rfc2217.html) remote serial ports and raw sockets using [*URL Handlers*](http://pythonhosted.org/pyserial/url_handlers.html#urls) such as rfc2217:://: respectively socket://: as *port* argument when invoking. Command line options python -m serial.tools.miniterm -h: usage: miniterm.py [-h] [--parity {N,E,O,S,M}] [--rtscts] [--xonxoff] [--rts RTS] [--dtr DTR] [-e] [--encoding CODEC] [-f NAME] [--eol {CR,LF,CRLF}] [--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 {N,E,O,S,M} set parity, one of {N E O S M}, 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 {CR,LF,CRLF} 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](http://pythonhosted.org/pyserial/tools.html#module-serial.tools.miniterm "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. # Examples[](http://pythonhosted.org/pyserial/examples.html#examples "Permalink to this headline") ## Miniterm[](http://pythonhosted.org/pyserial/examples.html#miniterm "Permalink to this headline") Miniterm is now available as module instead of example. see [*serial.tools.miniterm*](http://pythonhosted.org/pyserial/tools.html#miniterm) for details. [miniterm.py](https://github.com/pyserial/pyserial/blob/master/serial/tools/miniterm.py) The miniterm program. [setup-miniterm-py2exe.py](https://github.com/pyserial/pyserial/blob/master/examples/setup-miniterm-py2exe.py) This is a py2exe setup script for Windows. It can be used to create a standalone miniterm.exe. ## TCP/IP - serial bridge[](http://pythonhosted.org/pyserial/examples.html#tcp-ip-serial-bridge "Permalink to this headline") This program opens a TCP/IP port. When a connection is made to that port (e.g. with telnet) it forwards all data to the serial port and vice versa. This example only exports a raw socket connection. The next example below gives the client much more control over the remote serial port. * The serial port settings are set on the command line when starting the program. * There is no possibility to change settings from remote. * All data is passed through as-is. usage: tcp_serial_redirect.py [-h] [-q] [--parity {N,E,O,S,M}] [--rtscts] [--xonxoff] [--rts RTS] [--dtr DTR] [-P LOCALPORT] SERIALPORT [BAUDRATE] Simple Serial to Network (TCP/IP) redirector. positional arguments: SERIALPORT serial port name BAUDRATE set baud rate, default: 9600 optional arguments: -h, --help show this help message and exit -q, --quiet suppress non error messages serial port: --parity {N,E,O,S,M} set parity, one of {N E O S M}, 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) network settings: -P LOCALPORT, --localport LOCALPORT local TCP port NOTE: no security measures are implemented. Anyone can remotely connect to this service over the network. Only one connection at once is supported. When the connection is terminated it waits for the next connect. [tcp_serial_redirect.py](https://github.com/pyserial/pyserial/blob/master/examples/tcp_serial_redirect.py) Main program. ## Single-port TCP/IP - serial bridge (RFC 2217)[](http://pythonhosted.org/pyserial/examples.html#single-port-tcp-ip-serial-bridge-rfc-2217 "Permalink to this headline") Simple cross platform [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) serial port server. It uses threads and is portable (runs on POSIX, Windows, etc). * The port settings and control lines (RTS/DTR) can be changed at any time using [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) requests. The status lines (DSR/CTS/RI/CD) are polled every second and notifications are sent to the client. * Telnet character IAC (0xff) needs to be doubled in data stream. IAC followed by an other value is interpreted as Telnet command sequence. * Telnet negotiation commands are sent when connecting to the server. * RTS/DTR are activated on client connect and deactivated on disconnect. * Default port settings are set again when client disconnects. usage: rfc2217_server.py [-h] [-p TCPPORT] [-v] SERIALPORT RFC 2217 Serial to Network (TCP/IP) redirector. positional arguments: SERIALPORT optional arguments: -h, --help show this help message and exit -p TCPPORT, --localport TCPPORT local TCP port, default: 2217 -v, --verbose print more diagnostic messages (option can be given multiple times) NOTE: no security measures are implemented. Anyone can remotely connect to this service over the network. Only one connection at once is supported. When the connection is terminated it waits for the next connect. New in version 2.5. [rfc2217_server.py](https://github.com/pyserial/pyserial/blob/master/examples/rfc2217_server.py) Main program. [setup-rfc2217_server-py2exe.py](https://github.com/pyserial/pyserial/blob/master/examples/setup-rfc2217_server-py2exe.py) This is a py2exe setup script for Windows. It can be used to create a standalone rfc2217_server.exe. ## Multi-port TCP/IP - serial bridge (RFC 2217)[](http://pythonhosted.org/pyserial/examples.html#multi-port-tcp-ip-serial-bridge-rfc-2217 "Permalink to this headline") This example implements a TCP/IP to serial port service that works with multiple ports at once. It uses select, no threads, for the serial ports and the network sockets and therefore runs on POSIX systems only. * Full control over the serial port with [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html). * Check existence of /tty/USB0...8. This is done every 5 seconds using os.path.exists. * Send zeroconf announcements when port appears or disappears (uses python-avahi and dbus). Service name: _serial_port._tcp. * Each serial port becomes available as one TCP/IP server. e.g. /dev/ttyUSB0 is reachable at :7000. * Single process for all ports and sockets (not per port). * The script can be started as daemon. * Logging to stdout or when run as daemon to syslog. * Default port settings are set again when client disconnects. * modem status lines (CTS/DSR/RI/CD) are not polled periodically and the server therefore does not send NOTIFY_MODEMSTATE on its own. However it responds to request from the client (i.e. use the poll_modemoption in the URL when using a pySerial client.) usage: port_publisher.py [options] Announce the existence of devices using zeroconf and provide a TCP/IP serial port gateway (implements RFC 2217). If running as daemon, write to syslog. Otherwise write to stdout. optional arguments: -h, --help show this help message and exit serial port settings: --ports-regex REGEX specify a regex to search against the serial devices and their descriptions (default: /dev/ttyUSB[0-9]+) network settings: --tcp-port PORT specify lowest TCP port number (default: 7000) daemon: -d, --daemon start as daemon --pidfile FILE specify a name for the PID file diagnostics: -o FILE, --logfile FILE write messages file instead of stdout -q, --quiet suppress most diagnostic messages -v, --verbose increase diagnostic messages NOTE: no security measures are implemented. Anyone can remotely connect to this service over the network. Only one connection at once, per port, is supported. When the connection is terminated, it waits for the next connect. Requirements: * Python (>= 2.4) * python-avahi * python-dbus * python-serial (>= 2.5) Installation as daemon: * Copy the script port_publisher.py to /usr/local/bin. * Copy the script port_publisher.sh to /etc/init.d. * Add links to the runlevels using update-rc.d port_publisher.sh defaults 99 * Thats it :-) the service will be started on next reboot. Alternatively run invoke-rc.d port_publisher.sh start as root. New in version 2.5: new example [port_publisher.py](https://github.com/pyserial/pyserial/blob/master/examples/port_publisher.py) Multi-port TCP/IP-serial converter (RFC 2217) for POSIX environments. [port_publisher.sh](https://github.com/pyserial/pyserial/blob/master/examples/http://sourceforge.net/p/pyserial/code/HEAD/tree/trunk/pyserial/examples/port_publisher.sh) Example init.d script. ## wxPython examples[](http://pythonhosted.org/pyserial/examples.html#wxpython-examples "Permalink to this headline") A simple terminal application for wxPython and a flexible serial port configuration dialog are shown here. [wxTerminal.py](https://github.com/pyserial/pyserial/blob/master/examples/wxTerminal.py) A simple terminal application. Note that the length of the buffer is limited by wx and it may suddenly stop displaying new input. [wxTerminal.wxg](https://github.com/pyserial/pyserial/blob/master/examples/wxTerminal.wxg) A wxGlade design file for the terminal application. [wxSerialConfigDialog.py](https://github.com/pyserial/pyserial/blob/master/examples/wxSerialConfigDialog.py) A flexible serial port configuration dialog. [wxSerialConfigDialog.wxg](https://github.com/pyserial/pyserial/blob/master/examples/wxSerialConfigDialog.wxg) The wxGlade design file for the configuration dialog. [setup-wxTerminal-py2exe.py](https://github.com/pyserial/pyserial/blob/master/examples/setup-wxTerminal-py2exe.py) A py2exe setup script to package the terminal application. ## Unit tests[](http://pythonhosted.org/pyserial/examples.html#unit-tests "Permalink to this headline") The project uses a number of unit test to verify the functionality. They all need a loop back connector. The scripts itself contain more information. All test scripts are contained in the directory test. The unit tests are performed on port 0 unless a different device name or rfc2217:// URL is given on the command line (argv[1]). [run_all_tests.py](https://github.com/pyserial/pyserial/blob/master/test/run_all_tests.py) Collect all tests from all test* files and run them. By default, the loop:// device is used. [test.py](https://github.com/pyserial/pyserial/blob/master/test/test.py) Basic tests (binary capabilities, timeout, control lines). [test_advanced.py](https://github.com/pyserial/pyserial/blob/master/test/test_advanced.py) Test more advanced features (properties). [test_high_load.py](https://github.com/pyserial/pyserial/blob/master/test/test_high_load.py) Tests involving sending a lot of data. [test_readline.py](https://github.com/pyserial/pyserial/blob/master/test/test_readline.py) Tests involving readline. [test_iolib.py](https://github.com/pyserial/pyserial/blob/master/test/test_iolib.py) Tests involving the [io](http://docs.python.org/library/io.html#module-io "(in Python v2.7)") library. Only available for Python 2.6 and newer. [test_url.py](https://github.com/pyserial/pyserial/blob/master/test/test_url.py) Tests involving the [*URL*](http://pythonhosted.org/pyserial/url_handlers.html#urls) feature. # Appendix[¶](http://pythonhosted.org/pyserial/appendix.html#appendix "Permalink to this headline") ## How To[](http://pythonhosted.org/pyserial/appendix.html#how-to "Permalink to this headline") Enable [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html) in programs using pySerial. Patch the code where the [serial.Serial](http://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial "serial.Serial") is instantiated. Replace it with: try: s = serial.serial_for_url(...) except AttributeError: s = serial.Serial(...) Assuming the application already stores port names as strings that’s all that is required. The user just needs a way to change the port setting of your application to an rfc2217:// [*URL*](http://pythonhosted.org/pyserial/url_handlers.html#urls) (e.g. by editing a configuration file, GUI dialog etc.). Please note that this enables all [*URL*](http://pythonhosted.org/pyserial/url_handlers.html#urls) types supported by pySerial and that those involving the network are unencrypted and not protected against eavesdropping. Test your setup. Is the device not working as expected? Maybe it’s time to check the connection before proceeding. [*serial.tools.miniterm*](http://pythonhosted.org/pyserial/tools.html#miniterm) from the [*Examples*](http://pythonhosted.org/pyserial/examples.html#examples) can be used to open the serial port and do some basic tests. To test cables, connecting RX to TX (loop back) and typing some characters in [*serial.tools.miniterm*](http://pythonhosted.org/pyserial/tools.html#miniterm) is a simple test. When the characters are displayed on the screen, then at least RX and TX work (they still could be swapped though). ## FAQ[](http://pythonhosted.org/pyserial/appendix.html#faq "Permalink to this headline") Example works in [*serial.tools.miniterm*](http://pythonhosted.org/pyserial/tools.html#miniterm) but not in script. The RTS and DTR lines are switched when the port is opened. This may cause some processing or reset on the connected device. In such a cases an immediately following call to write() may not be received by the device. A delay after opening the port, before the first write(), is recommended in this situation. E.g. a time.sleep(1) Application works when .py file is run, but fails when packaged (py2exe etc.) py2exe and similar packaging programs scan the sources for import statements and create a list of modules that they package. pySerial may create two issues with that: * implementations for other modules are found. On Windows, it’s safe to exclude ‘serialposix’, ‘serialjava’ and ‘serialcli’ as these are not used. * [serial.serial_for_url()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.serial_for_url "serial.serial_for_url") does a dynamic lookup of protocol handlers at runtime. If this function is used, the desired handlers have to be included manually (e.g. ‘serial.urlhandler.protocol_socket’, ‘serial.urlhandler.protocol_rfc2217’, etc.). This can be done either with the “includes” option in setup.py or by a dummy import in one of the packaged modules. User supplied URL handlers [serial.serial_for_url()](http://pythonhosted.org/pyserial/pyserial_api.html#serial.serial_for_url "serial.serial_for_url") can be used to access “virtual” serial ports identified by an [*URL*](http://pythonhosted.org/pyserial/url_handlers.html#urls) scheme. E.g. for the [**RFC 2217**](http://tools.ietf.org/html/rfc2217.html): rfc2217:://. Custom [*URL*](http://pythonhosted.org/pyserial/url_handlers.html#urls) handlers can be added by extending the module search path in [serial.protocol_handler_packages](http://pythonhosted.org/pyserial/pyserial_api.html#serial.protocol_handler_packages "serial.protocol_handler_packages"). This is possible starting from pySerial V2.6. ## Related software[](http://pythonhosted.org/pyserial/appendix.html#related-software "Permalink to this headline") com0com - [http://com0com.sourceforge.net/](http://com0com.sourceforge.net/) Provides virtual serial ports for Windows. ## License[](http://pythonhosted.org/pyserial/appendix.html#license "Permalink to this headline") Copyright (c) 2001-2015 Chris Liechti All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: > * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. > * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. > * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.