识别.py文件的变量并打印它们的 Python 程序



我需要创建一个程序来查找.py文件的所有变量(全局和局部(并打印它们。 但是我不知道如何在另一个.py文件上使用函数 dir(( 或全局((/local(( 来搜索变量。

你能帮我吗? def identifyVariables(name(:

file = open (name,'r')
variablesStr = "The variables on code are: n"
contL=0
for linea in file:
contL = contL + 1
pos = linea.find(str(dir()))
#No se donde meter el for para pegarlo con el po
if(pos>-1):
variablesStr += linea[pos+1:len(linea)] + ": line " + contL
file.close()
print(variablesStr)

你想写"一个找到所有变量的程序"。我想提前警告你,如果你关心彻底性,Python会让这件事变得异常困难。如果你不这样做,就像你只是在寻找最常见的foo = "bar"情况一样,很好:你可以使用 ast.parse 这样的东西来寻找变量赋值,这可能会让你 99% 的方式到达那里。

但是,如果您的目标是查找模块中的每个变量,请考虑以下代码片段:

vars().update({"spam": "eggs"})
print(spam)

寻找变量赋值的方法不会发现这一点。另外,考虑到给定模块可能具有由其他内容设置的变量:

>>> import requests
>>> requests.spam
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'requests' has no attribute 'spam'
>>> setattr(requests, 'spam', 'eggs')
>>> requests.spam
'eggs'

对于用作配置设置等存储的模块来说,这种情况并不少见。

最新更新