我想构建一个程序(使用Python),该程序正在分析其他Python脚本。因此,我需要一种使Python程序可读的.py文件的方法。
我曾考虑过将.py转换为.txt,然后使用.startswith和.find方法。有没有办法将.py转换为.txt?
也可以随时告诉其他分析方法。重要的是要弄清楚诸如if语句或循环以及缩进级别之类的结构。
事实证明这是一项非常艰巨的任务,我通过以下限制解决了该问题,已检查的文件应位于另一个文件夹中(否则,我的Pycharm IDE会被筛选为它们=始终处于打开状态),要检查的文件应为在检查时关闭。因此,您应该打开文件,进行修改,保存然后关闭。在这种情况下,程序可以正常工作。
import os
from datetime import datetime
import time
def check_py_files(files, _path):
for file in files:
if file.endswith(".py") and file != "checker.py":
f = open(_path + "\\" + file, mode='r')
for line in f:
if "AAA" in line:
print("AAA detected in {}".format(file))
break
else:
print("{} is fine".format(file))
f.close()
del f
if __name__ == "__main__":
while True:
files = os.listdir("C:\\Users\\LOL.000\\Desktop\\test") # path to files in my Windows PC
print(files)
print(datetime.now())
check_py_files(files, "C:\\Users\\LOL.000\\Desktop\\test")
time.sleep(10)
输出:
['another.py', 'x.py']
2019-11-03 17:10:19.811678
AAA detected in another.py
AAA detected in x.py
['another.py', 'x.py']
2019-11-03 17:10:29.819931
AAA detected in another.py
AAA detected in x.py
['another.py', 'x.py']
2019-11-03 17:10:39.820054
another.py is fine
AAA detected in x.py
['another.py', 'x.py']
2019-11-03 17:10:49.824967
another.py is fine
AAA detected in x.py
['another.py', 'x.py']
2019-11-03 17:10:59.825455
another.py is fine
x.py is fine
['another.py', 'x.py']
2019-11-03 17:11:09.826578
another.py is fine
x.py is fine
['another.py', 'x.py']
2019-11-03 17:11:19.828198
AAA detected in another.py
AAA detected in x.py
['another.py', 'x.py']
2019-11-03 17:11:29.829994
AAA detected in another.py
AAA detected in x.py
['another.py', 'x.py']
2019-11-03 17:11:39.831648
AAA detected in another.py
AAA detected in x.py
['another.py', 'x.py']
2019-11-03 17:11:49.832690
AAA detected in another.py
AAA detected in x.py
['another.py', 'x.py']
2019-11-03 17:11:59.833810
AAA detected in another.py
AAA detected in x.py
['another.py', 'x.py']
2019-11-03 17:12:09.834953
AAA detected in another.py
x.py is fine
['another.py', 'x.py']
2019-11-03 17:12:19.836385
another.py is fine
x.py is fine
也可以随时告诉其他分析方法。重要的是要弄清楚诸如if语句或循环以及缩进级别之类的结构。
如果要以与Python本身解析文件完全相同的方式保留这种结构,则应使用标准库ast
模块(https://docs.python.org/3/library/ast.html)。 AST的意思是“抽象语法树”:Python理解的代码表示形式。
基本用法是在要解析的文件上调用ast.parse(file)
(https://docs.python.org/3/library/ast.html#ast.parse)。您将获得一个对象(https://docs.python.org/3/library/ast.html#ast.AST),它是AST节点树的顶部。
您可能有兴趣挑选black
(https://github.com/psf/black)的源代码,这是一个Python代码格式化程序,它使用ast
来验证格式化后的代码与原始代码具有完全相同的行为。运行。