转载 2011年11月17日 22:20:24



This module encapsulates the access for the serial port. It provides backends for Python running on Windows, Linux, BSD (possibly any POSIX compliant system), Jython and IronPython (.NET and Mono). The module named "serial" automatically selects the appropriate backend.

It is released under a free software license, see LICENSE.txt for more details.
(C) 2001-2008 Chris Liechti

The project page on SourceForge and here is the SVN repository and the Download Page .
The homepage is on


  • same class based interface on all supported platforms
  • access to the port settings through Python 2.2+ properties
  • port numbering starts at zero, no need to know the port name in the user program
  • port string (device name) can be specified if access through numbering is inappropriate
  • support for different bytesizes, stopbits, parity and flow control with RTS/CTS and/or Xon/Xoff
  • working with or without receive timeout
  • file like API with "read" and "write" ("readline" etc. also supported)
  • The files in this package are 100% pure Python. They depend on non standard but common packages on Windows (pywin32) and Jython (JavaComm). POSIX (Linux, BSD) uses only modules from the standard Python distribution)
  • The port is set up for binary transmission. No NULL byte stripping, CR-LF translation etc. (which are many times enabled for POSIX.) This makes this module universally useful.


  • Python 2.2 or newer
  • pywin32 extensions on Windows
  • "Java Communications" (JavaComm) or compatible extension for Java/Jython


from source

Extract files from the archive, open a shell/console in that directory and let Distutils do the rest:
python install

The files get installed in the "Lib/site-packages" directory.


An EGG is available from the Python Package Index:
easy_install pyserial

windows installer

There is also a Windows installer for end users. It is located in the Download Page
Developers may be interested to get the source archive, because it contains examples and the readme.

Short introduction

Open port 0 at "9600,8,N,1", no timeout
<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
import serial
ser = serial.Serial(0)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
ser.close()             # close port
Open named port at "19200,8,N,1", 1s timeout
<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)
x =          # read one byte
s =        # read up to ten bytes (timeout)
line = ser.readline()   # read a '\n' terminated line
Open second port at "38400,8,E,1", non blocking HW handshaking
<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
ser = serial.Serial(1, 38400, timeout=0, parity=serial.PARITY_EVEN, rtscts=1)
s =       # read up to one hundred bytes
...                     # or as much is in the buffer
Get a Serial instance and configure/open it later
<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
>>> ser = serial.Serial()
>>> ser.baudrate = 19200
>>> ser.port = 0
>>> ser
Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
>>> ser.isOpen()
>>> ser.close()
>>> ser.isOpen()
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.


Please look in the SVN Repository. There is an example directory where you can find a simple terminal and more.

Parameters for the Serial class

<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
ser = serial.Serial(
port=None,              # number of device, numbering starts at
# zero. if everything fails, the user
# can specify a device string, note
# that this isn't portable anymore
# if no port is specified an unconfigured
# an closed serial port object is created
baudrate=9600,          # baud rate
bytesize=EIGHTBITS,     # number of databits
parity=PARITY_NONE,     # enable parity checking
stopbits=STOPBITS_ONE,  # number of stopbits
timeout=None,           # set a timeout value, None for waiting forever
xonxoff=0,              # enable software flow control
rtscts=0,               # enable RTS/CTS flow control
interCharTimeout=None   # Inter-character timeout, None to disable
The port is immediately opened on object creation, if a port is given. It is not opened if port is None.
Options for read timeout:
<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
timeout=None            # wait forever
timeout=0               # non-blocking mode (return immediately on read)
timeout=x               # set timeout to x seconds (float allowed)

Methods of Serial instances

<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
open()                  # open port
close()                 # close port immediately
setBaudrate(baudrate)   # change baud rate on an open port
inWaiting()             # return the number of chars in the receive buffer
read(size=1)            # read "size" characters
write(s)                # write the string s to the port
flushInput()            # flush input buffer, discarding all it's contents
flushOutput()           # flush output buffer, abort output
sendBreak()             # send break condition
setRTS(level=1)         # set RTS line to specified logic level
setDTR(level=1)         # set DTR line to specified logic level
getCTS()                # return the state of the CTS line
getDSR()                # return the state of the DSR line
getRI()                 # return the state of the RI line
getCD()                 # return the state of the CD line

Attributes of Serial instances

Read Only:
<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
portstr                 # device name
BAUDRATES               # list of valid baudrates
BYTESIZES               # list of valid byte sizes
PARITIES                # list of valid parities
STOPBITS                # list of valid stop bit widths
New values can be assigned to the following attributes, the port will be reconfigured, even if it's opened at that time:

<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
port                    # port name/number as set by the user
baudrate                # current baud rate setting
bytesize                # byte size in bits
parity                  # parity setting
stopbits                # stop bit with (1,2)
timeout                 # timeout setting
xonxoff                 # if Xon/Xoff flow control is enabled
rtscts                  # if hardware flow control is enabled


<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->


<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->
<!-- /* GeSHi (c) Nigel McNie 2004 ( */ .text .imp {font-weight: bold; color: red;} -->


在上下载最新的windows版的安装包,然后装到python的目录下面,我装到了2.5的下面。打开一个python ...
  • xbl1986
  • xbl1986
  • 2011-04-11 13:56:00
  • 18813

树莓派+Python+pyserial 2.7实现串口通信

手上有个CCD Camera(Barcode Reader/Scanner Module),它是通过RS232通信的,用RS232转USB的转接线连接树莓派,即可完成硬件连接。对于串口通信,可以通过p...
  • Burgess_Liu
  • Burgess_Liu
  • 2014-12-05 11:48:10
  • 36331


安装pyserialpip install pyserial查看可用的端口# coding:utf-8import = list(serial...
  • log1100
  • log1100
  • 2017-01-12 17:54:44
  • 14989


一、概述     pyserial模块封装了对串口的访问。 二、特性     在支持的平台上有统一的接口。     通过python属性访问串口设置。     支持不同的字节...
  • huayucong
  • huayucong
  • 2015-09-25 10:41:15
  • 26363


笔者在用pyserial打开虚拟串口时出现了一些问题,最后发现是python版本的问题,现将几种情况总结如下 1.实际串口#查询串口号 geek@geek-Lenovo-G40-70:~/Docum...
  • weixin_38685248
  • weixin_38685248
  • 2017-05-07 18:55:26
  • 412


简述一个python项目需要用到PC的串口时,一般会在Application code中看到会有类似“import serial”的操作,如果没有安装serial module,那么在运行.py脚本时...
  • suxiang198
  • suxiang198
  • 2016-07-28 16:08:03
  • 6280


pySerial Overview This module encapsulates the access for the serial port. It provides backends ...
  • BBZZ2
  • BBZZ2
  • 2016-07-25 17:22:27
  • 1527

解决 ImportError: No module named 'serial' 问题

在pycharm里编写Python串口程序的时候,编译时提示 ImportError: No module named 'serial' 解决办法: 安装 serial mod...
  • jiangchao3392
  • jiangchao3392
  • 2017-07-14 14:23:35
  • 2053


  • hcx25909
  • hcx25909
  • 2016-01-18 17:12:10
  • 8185


Python+Pycharm使用opencv在这个配置过程中,也遇到了不少的问题,写出此篇博文,希望可以帮到一些可以与我遇到相同问题的人。 主要步骤: 1.Anaconda2的下载:传送门 ...
  • whykifan
  • whykifan
  • 2017-03-26 19:53:22
  • 4965