Create a variable "on the fly"

Scott David Daniels Scott.Daniels at Acm.Org
Thu Jul 28 11:45:02 EDT 2005


Paul D.Smith wrote:
>... What I'm left with is the following...
> 1. A shell script which I maintain.
> 2. A simple Python config which searches for all shell environment variables
> named "MY_..." and instantiates then as Python variables.
> 3. Historical scripts that run without me needing to spend time hunting down
> all the config variables and replacing them with os.environ['MY_...'].

Suppose you have a module named 'MY', with MY.py as:

     import os
     _globals = globals()
     for _name, _entry in os.environ.iteritems():
         if _name.startswith('MY_'):
             try:
                 _entry = int(_entry)
             except ValueError:
                 try:
                     _entry = float(_entry)
                 except ValueError:
                     pass
             _globals[_name[3 :]] = _entry

then, wherever your python scripts use MY_XYZ, you begin the script
with "import MY" and change every "MY_XYZ" to "MY.XYZ".


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list