How To Change A Variable Value In A Python File From A Python Script
Solution 1:
The short answer is: don't. It won't be worth the trouble.
It sounds like you are trying to create a configuration file and then have your application update it. You should try using ConfigParser, a built-in module that can read and write configuration files for you with limited hassle: http://docs.python.org/library/configparser.html
Solution 2:
currently have a python file with a bunch of global variables with values
Let's pretend it looks like this. globals.py
this = 1that = 2
And there's nothing else in this file. Nothing.
Let's further pretend that this file is used as follows.
fromglobalsimport *
Let's further pretend that we have some simulation which needs to "update" globals.py
import osos.rename( "globals.py", "globals.bak" )
with open( "globals.py", "w" ) as target:
for variable in ('some', 'list', 'of', 'sensible', 'globals'):
target.write( "{0!s} = {1!r}".format( variable, globals()[variable] )
Basically, you recreate Python code from your global dictionary.
This is a dreadful solution. Please don't actually use it.
Post a Comment for "How To Change A Variable Value In A Python File From A Python Script"