abstract syntax tree - Python : Evaluating string of python code -
i trying create python script generation tool create python files based on actions. example:
action = "usb" # dynamic input script dev_type = "3.0" # dynamic input script configuration import config if action == "usb": script = """ #code usb functionality dev_type = """ + dev_type + """ if dev_type == "2.0" command = config.read("usb command 2.0 ") proc = subprocess.popen(command,stdout=subprocess.pipe, stderr=subprocess.pipe, shell=false) elif dev_type == "3.0": command = config.read("usb command 3.0 ") proc = subprocess.popen(command,stdout=subprocess.pipe, stderr=subprocess.pipe, shell=false) """ elif action == "lan": script = """ #code run lan functionality eg: command = config.read("lan command") proc = subprocess.popen(command,stdout=subprocess.pipe, stderr=subprocess.pipe, shell=false) """ open("outputfile.py", w) fl: fl.writelines(script)
the actual script generator complex. generate "outputfile.py" script in local machine inputting action script , deploy script generated remote machines record results. part of larger framework , need keep execution format.
each "script" block uses config.read function read variables required run config file. "command" in above example.
my actual frame work has 800 configurations in config file - deploy on remote machines along script run. there lot of configurations in file may not required particular script run , not user friendly.
what looking based on "script" block written output file - create custom config file contains config required script run.
for example if action "lan", below script block written output file
script = """ #code run lan functionality eg: command = config.read("lan command") proc = subprocess.popen(command,stdout=subprocess.pipe, stderr=subprocess.pipe, shell=false) """
what want "lan command" in custom config file.
my question : how evaluate "script" block (inside triple quotes) know config been used in code , write config custom config file when write output file ?
there multiple if conditions inside "script" block also. not want config "usb command 2.0" , "usb command 3.0" in custom config file if action = "usb" , dev_type = "3.0"
of course cannot execute code inside "script" block - , intercept config.read() function write config got called custom config file. there better way ?
Comments
Post a Comment