LISTINg 10-8:
Displaying the environment variables using the .NET method
# Obtain access to Environment class properties.
from System import Environment
# Obtain all of the Environment class methods.
from System.Environment import *
548592c10.indd 214
2/24/10 12:48:33 PM
www.finebook.ir
Interacting with the Environment
❘
215
# Import the EnvironmentVariableTarget enumeration.
from System import EnvironmentVariableTarget
# Display specific, standard environment variables.
print ‘Standard Environment Variables:’
print ‘\tCurrent Directory:’, Environment.CurrentDirectory
print ‘\tOS Version:’, Environment.OSVersion
print ‘\tUser Name:’, Environment.UserName
# Display any single environment variable.
print ‘\nSpecific Environment Variables:’
print ‘\tIronPython Path:’, GetEnvironmentVariable(‘IronPythonPath’)
print ‘\tSession Name:’, GetEnvironmentVariable(‘SessionName’)
# Display a particular kind of environment variable.
print ‘\nUser Level Environment Variables:’
for Var in GetEnvironmentVariables(EnvironmentVariableTarget.User):
print ‘\t%s: %s’ % (Var.Key, Var.Value)
# Display all of the environment variables in alphabetical order.
print ‘\nAll of the environment variables.’
# Create a list to hold the variable names.
Keys = GetEnvironmentVariables().Keys
Variables = []
for Item in Keys:
Variables.Add(Item)
# Sort the resulting list.
Variables.sort()
# Display the result.
for Var in Variables:
print ‘\t%s: %s’ % (Var, GetEnvironmentVariable(Var))
# Pause after the debug session.
raw_input(‘\nPress any key to continue...’)
The code begins by importing some .NET assemblies. Notice that the example reduces clutter by
importing only what the code actually needs.
As mentioned earlier, you can obtain standard environment variable values by using the correct
property value from the
System.Environment
class. In this case, the code retrieves the current
directory, operating system version, and the user name, as shown in Figure 10-13.
The next code segment in Listing 10-8 shows how to obtain a single environment variable. All you
need is the
GetEnvironmentVariable()
with a variable name, such as,
IronPythonPath
.
If you want to work with the environment variables found at a particular level, you use
GetEnvironmentVariables()
with an
EnvironmentVariableTarget
enumeration value, as
shown in the next code segment in Listing 10-8. Unless you create a custom environment variable,
you won’t see any output at the
EnvironmentVariableTarget.Process
level.
548592c10.indd 215
2/24/10 12:48:33 PM
www.finebook.ir
Do'stlaringiz bilan baham: |