python如何判断一个文件是否处于打开状态?


我想在服务器端获取用户请求的文件状态,如是否打开,打开数等。代码如何实现?

web python2.7 python-flask

大灰狼 9 years, 9 months ago

请问你的是linux吗?如果是linux可以借助/proc来获取。


 import os

class File(object):
    def __init__(self, file_path):
        if not os.path.exists(file_path):
            raise OSError('{file_path} not exist'.format(file_path = file_path))
        self.file_path = os.path.abspath(file_path)

    def status(self):
        open_fd_list = self.__get_all_fd()
        open_count = len(open_fd_list)
        is_opened = False
        if open_count > 0:
            is_opened = True

        return {'is_opened': is_opened, 'open_count': open_count}

    def __get_all_pid(self):
        """获取当前所有进程"""
        return [ _i for _i in os.listdir('/proc') if _i.isdigit()]

    def __get_all_fd(self):
        """获取所有已经打开该文件的fd路径"""
        all_fd = []
        for pid in self.__get_all_pid():
            _fd_dir = '/proc/{pid}/fd'.format(pid = pid)
            if os.access(_fd_dir, os.R_OK) == False:
                continue

            for fd in os.listdir(_fd_dir):
                fd_path = os.path.join(_fd_dir, fd)
                if os.path.exists(fd_path) and os.readlink(fd_path) == self.file_path:
                    all_fd.append(fd_path)

        return all_fd

if __name__ == "__main__":
    _file = File('/tmp/a.txt')
    print(_file.status())

微小D轨迹 answered 9 years, 9 months ago

Your Answer