Pyse configuration file

I need to write a python script that reads and parses a python file for customization. settings contain some variables and function calls.

Example:

setup.py x = 5 mylist [ 1, 2, 3] myfunc(4) myfunc(5) myfunc(30) main.py . parse_setup('setup.py') . 

I would like to analyze the installation file and “see” which variables were defined and which function calls. since the installation file is written in python, I thought that the easiest way would be to dynamically import the installation file (dynamically, because the path to the installation file is the input for the main one).

the problem is that the import fails because myfucn() called in setup.py is not defined.

is there any way to intercept myfunc() calls in setup.py and execute my own function defined in main.py ?

What if the function I want to execute is a member function?

can anyone think of a better way to extract the data in the installation file, I really do not want to read it in turn.

Thanks!

+4
source share
2 answers

If your setup.py contains these Python instructions:

 x = 5 mylist = [ 1, 2, 3] y = myfunc(4) z = myfunc(x) 

You can do something like this in main.py to find out what it defined:

 def myfunc(n): return n**2 def parse_setup(filename): globalsdict = {'__builtins__': None, 'myfunc': myfunc} # put predefined things here localsdict = {} # will be populated by executed script execfile(filename, globalsdict, localsdict) return localsdict results = parse_setup('setup.py') print results # {'y': 16, 'x': 5, 'z': 25, 'mylist': [1, 2, 3]} 
+1
source

If setup.py is valid for python, you can use execfile () or import ().

execfile is close to what you seem to be looking for.

setup.py

 def function(): print "called" 

main.py

 execfile("setup.py") function() # will print called 

http://docs.python.org/2/library/functions.html#execfile

After reviewing your question again, a better example might be:

setup.py

 func("one") func("two") 

main.py

 def func(s): print s execfile("setup.py") # will print: # one # two 

Please note that file upload should be done after the function definitions.

0
source

Source: https://habr.com/ru/post/1443959/


All Articles