Sunday, April 3, 2011

Env Variables in Python (v3.0) on Windows

Hello all. I'm using Python 3.0.

How to expand an environment variable given the %var_name% syntax?

Any help is much appreciated! Thanks!

From stackoverflow
  • I'm guessing you mean "How do I get environment variables?":

    import os
    username = os.environ['UserName']
    

    Alternatively, you can use:

    username = os.getenv('UserName')
    

    And to add/change your own variables, you can use:

    os.putenv('MyVar', 'something I want to store')
    
  • It's in a slightly unexpected place: os.path.expandvars(). Admittedly it is quite often used for processing paths:

    >>> import os.path
    >>> os.path.expandvars('%APPDATA%\\MyApp')
    'C:\\Documents and Settings\\Administrator\\Application Data\\MyApp'
    

    but it's a shell function really.

0 comments:

Post a Comment