1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Development programming, environmental variables

Discussion in 'Software' started by marcboy, 16 Jul 2004.

  1. marcboy

    marcboy What's a Dremel?

    Joined:
    19 Apr 2003
    Posts:
    25
    Likes Received:
    0
    Ok im writing a python script which reads from a file in a specific location, does anyone know if theres a way to use the windows environmental variables to give the path to the file, for example the %SYSTEMDRIVE% variable incase people dont have C:\ as their mine drive.

    Thanx :rock:
     
  2. Mac Logo

    Mac Logo What's a Dremel?

    Joined:
    19 Apr 2004
    Posts:
    1
    Likes Received:
    0
    GIYF

    From Red Hat® Linux 6 Unleashed Chapter 34: Programming in Python

    (but AFAIK it's the same deal under Windows.)

    Environment variables are accessed in Python through the os module's environ dictionary. Because it's a dictionary, lookups are done with the os.enEviron[VARNAM] syntax, with the environment variable's name in quotes. That syntax throws a KeyError exception if VARNAME isn't in the environment. Unfortunately, an missed KeyError exception will clumsily terminate the program. To prevent that, the try, except, else syntax is used to handle any KeyError exception. Note the following code:

    Code:
    #!/usr/bin/python 
    import os
    
    def printenv(s):
       try:
          x = os.environ[s]
       except KeyError:
          print "No such environment var:", s
       else:
          print "Env var", s, "has value:", x
    
    printenv("SHELL")
    printenv("OSTYPE")
    
    Cheers

    Graeme
     

Share This Page