#!/usr/bin/python2 print """ Variable Grabbler - version 3.4 -------------------------------""" ################################################################ # Changes in this version: #=============================================================== # * added support for command execution # * some internal technicalities that should not impact features # * Yes. # ################################################################ # Exit codes: #=============================================================== # 0 => normal exit # 1 => argument error # 2 => error while processing # # definitions import os, json, sys, subprocess def print_err(text): print >> sys.stderr, text if not len(sys.argv)==3: print_err("Error: Exactly two arguments required: \"python variable_grabbler.py \"") sys.exit(1) print "Reading config file...", config_file = open(sys.argv[2],"r") config_values = json.loads(config_file.read().decode("utf-8")) config_file.close() print "Done." print "Working on file: "+sys.argv[1] for variable in config_values: print "> "+variable+" => ", file_in = open(sys.argv[1], "r") file_content = file_in.read() file_in.close() if config_values[variable][0] == "file": print "Found array. Adding file instead: " + config_values[variable][1] file_replacement = open(config_values[variable][1], "r") replacement = file_replacement.read() file_replacement.close() elif config_values[variable][0] == "exec": print "Found array. Executing command instead: " + config_values[variable][1] process = subprocess.Popen(config_values[variable][1], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode == 0: print "Process exited normally. Replacing variable with the output from STDOUT..." print_err("Subprocess exited normally.\nThe following error messages were produced:") print_err(stderr) replacement = stdout else: print "Process exited abnormally. Exiting. No changes will be made." print_err("Subprocess exited abnormally. Exiting.\nThe following output was produced:") print_err(stdout) print_err("The following error messages were produced:") print_err(stderr) print "Exiting now." sys.exit(2) else: replacement = config_values[variable] print repr(replacement) file_out = open(sys.argv[1], "w") file_out.write(file_content.decode('utf-8').replace("%" + variable.upper() + "%", replacement).encode('utf-8')) file_out.close() print "Done."