I have a file with the contents
a = 24
b = 1.2
def test(x, y):
return x + y
I would like to parse this file to retrieve the information that
- it contains the two variables
aandb,- their values,
- it contains a function called
test- which has two input arguments and
- which returns their sum.
(I would like to use this info to create another file.)
How to do that?
What I have tried
I can parse it with Python 3 using
global_vars = {}
local_vars = {}
namespace = {}
with open(args.infile) as f:
code = compile(f.read(), args.infile, 'exec')
exec(code, global_vars, local_vars)
after which I get
testfunction = local_vars['test']
There are a couple of things I can find out about test from the testfunction object, for example the names of variables and the byte code via
testfunction.func_code.co_varnames
testfunction.func_code.co_code
However, I don't know where to go from here.
ast.