Looking For A Way To Identify And Replace Python Variables In A Script
I have a dictionary of variablenames and I want those to be the variablenames in another script. So I probably need to identify all variables in a Python script and then somehow r
Solution 1:
Python can read python. So write a script with that dictionary that looks at your first script and uses regex to replace the correct symbols. Make the file you want to modify an in file and read it, edit it, and write it back to the .py file line by line.
heres doc on file I/O in python just in case you need it:
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
Solution 2:
To assign global variables using a dictionary from another module:
from other_module import desired_dictionary
if __name__=="__main__":
import this_module
for name, value in desired_dictionary.items():
setattr(this_module, name, value)
Solution 3:
I now chose to simply identify variables as the last word coming before a "=" character in a script. (Does that make sense?) I use
line.split("=")[0].split(" ")[-1]
to identify those words after opening the script as proposed by NKamrath with
f = open('replaceme.py')
f.readlines()
Thanks a lot for the help so far!
Post a Comment for "Looking For A Way To Identify And Replace Python Variables In A Script"