Python没有关闭文件描述符

Shi*_*tee 8 python linux

我正在开发一个长期运行的python脚本,它可以连接到不同的串口.该脚本在执行过程中崩溃了几个小时,引用了"打开太多文件".

我已经跟踪了串口模块的问题,其中.close()方法似乎没有减少python正在使用的文件描述符的数量.我正在检查这个lsof | grep python | wc.使用Debian 7.2和Python 2.7.3

下面的示例慢慢使用越来越多的文件描述符,直到达到限制.为什么这样,我怎么能避免它?

#!/usr/bin/env python
import serial                   #Used to communicate with pressure controller
import logging
import time
from time import gmtime, strftime
logging.basicConfig(filename="open_files_test.log")

# Write unusual + significant events to logfile + stdout
def log( message ):
    time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
    logging.warning( time + " " + message )
    print( message )

for i in range(2000):
    for n in range(1, 12):
        try:
            port_name = "/dev/tty" + str(n+20)
            com = serial.Serial(port_name,9600,serial.EIGHTBITS,serial.PARITY_NONE,serial.STOPBITS_ONE,0.0,False,False,5.0,False,None)
            com.open()
            com.flushInput()
            com.flushOutput()
            log("Opened port: " + port_name)
        except serial.SerialException:
            com = None
            log("could not open serial port: " + port_name)

        com.close()
        log("Closed port: " + port_name)
        time.sleep(1)

log("Finished Program")
Run Code Online (Sandbox Code Playgroud)

谢谢

kha*_*hik 5

似乎额外com.open造成了这个问题.根据文档 serial.Serial返回它打开,所以你不需要再次打开它.在Linux中(据我所知,所有POSIX都open只是增加计数器,关闭只是递减计数器).这里有一个删除的答案@wheaties建议使用with我也推荐:

with serial.Serial(port_name, 9600, ...) as com:
    com.flushInput()
    com.flushOutput()
    ...
Run Code Online (Sandbox Code Playgroud)