Last active
May 28, 2019 05:46
-
-
Save hidva/f8f3aefd07558e7941205fe4a3721eeb to your computer and use it in GitHub Desktop.
python, 移除未被打开的文件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import os | |
import sys | |
import logging | |
logging.basicConfig(format="%(asctime)s|%(process)d|%(thread)d|%(name)s|%(levelname)s|%(message)s", level=logging.INFO) | |
def opened_info(path): | |
""" | |
返回 [(pid, fd), (pid, fd), ...]; 表明 pid 指定的进程打开了文件 path, 而且文件描述符是 fd. | |
""" | |
origin_stat = os.stat(path) | |
ret = [] | |
for pidstr in os.listdir('/proc'): | |
if not pidstr.isdigit(): | |
continue # pidstr 不是一个合法的进程 id. | |
pidfddir = os.path.join('/proc', pidstr, 'fd') | |
try: | |
pidfds = os.listdir(pidfddir) | |
except: | |
logging.exception('os listdir failed, dir: %s', pidfddir) | |
continue | |
for pidfdstr in pidfds: | |
if not pidfdstr.isdigit(): | |
continue | |
try: | |
pidfdstat = os.stat(os.path.join(pidfddir, pidfdstr)) | |
except: | |
continue | |
if os.path.samestat(origin_stat, pidfdstat): | |
ret.append((int(pidstr), int(pidfdstr))) | |
return ret | |
if __name__ == '__main__': | |
for filename in sys.argv[1:]: | |
oi = opened_info(filename) | |
if not oi: | |
os.remove(filename) | |
logging.info('remove file; filepath: %s', filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment