统计一个C工程都使用了哪些头文件
读程序的时候想看看整个工程都使用了哪些系统头文件,找不到现成的命令可以用,就赶快打开python写个,刚好是个练习的好机会。
先在工程目录中把包含include的行都输入到一个文件“log”中:
grep "#include" * -r --color > log
以前只看过语法,还是第一次正真使用,所以几乎每一个函数都是从百度上现搜现用。
with open("log", "rw") as file: store = [] for line in file: _, _, data = line.partition("#include ") # grep生成的行包含里文件名,不需要,所以存在第一个“_”里,
# 第二个"_"存的是“#include ”本身,
# 第三个是我想要的数据,后面包含了一个"\n"换行符。 if not data in store: # 去掉重复的头文件名 store.append(data) store.sort() # 排序后打印出来好看一些 for element in store: print element, # store中的元素已经包含换行符了,把print函数自动加的去掉,好像只能用加个“,”的办法。 print len(store) # 看一共include了多少个文件
同事提醒去重可以使用集合的,那就改个用集合版本的。不过要排序打印出来,还是要变回list。
with open("log", "rw") as file: store = set() for line in file: _, _, data = line.partition("#include ") store.add(data) store = sorted(store) for element in store: print element, print len(store)
加了新需求,就是不想打印出有双引号include的头文件,只想要“<>”包含的系统头文件。再多用一个函数startswith就行了。
with open("log", "rw") as file: store = set() for line in file: _, _, data = line.partition("#include ") if not data.startswith('"'): store.add(data) store = sorted(store) for element in store: print element, print len(store)
python真的是很方便,建议所有使用电脑的人都学一学。不论你是搞IT的,还是搞其他工程类的,甚至处在文科类的行业,都可以通过python来更好的使用你的电脑。
浙公网安备 33010602011771号