I have been trying to read python files and print its variables for a while now. Is it possible to view and print the variables of another file without importing or running it? Everything I have already searched only explains how to import or use execfile, etc... (disclaimer, I am probably dumb)
This is what I have so far:
for vars in dir():
print(vars)
Now, this works perfectly fine for the file it is being run from, but when I try this code:
for vars in file:
print(vars)
(file is simply path.read())
Well, it gives me every character of the file on a new line. I have no idea if my loop is correct at all. Will I have to write something that will manually find each variable, then add it into a list?
Use ast.parse
to parse the code, recursively traverse the nodes by iterating through those with a body
attribute (which are code blocks), look for Assign
objects and get their targets
(which are the variables being assigned with values, which are what you're looking for) and get their id
attribute if they are Name
objects.
Try the following code after replacing file.py
with the file name of the python script you want to parse.
import ast
import _ast
def get_variables(node):
variables = set()
if hasattr(node, 'body'):
for subnode in node.body:
variables |= get_variables(subnode)
elif isinstance(node, _ast.Assign):
for name in node.targets:
if isinstance(name, _ast.Name):
variables.add(name.id)
return variables
print(get_variables(ast.parse(open('file.py').read())))
No ... and yes.
The question is whether the "variables" are constants or true variables.
Python runs a garbage collector. It will create the variables when you run/import a module. These variables will have scope based on how they are used. Once they are no longer in use, the garbage collector will remove the objects from memory.
If the variable is assigned a fixed value (e.g. i = 1
) then you can simply read the file in as if it is a text file - since it is a text file. If you want to change those variables, you can simply write it out as a text file. It will be incumbent on you to trace the variables in the text, exactly as with any text matching.
If the variables are generated as part of the code, then no (e.g. it generates a list of file in a directory and assigns to a variable). You would need to either import the module, or change the module so that it exports the outputs to a separate file - e.g. csv - and then you can read the data file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With