Interacting with the Environment
❘
217
LISTINg 10-9:
Setting an environment variable 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 *
# Import the EnvironmentVariableTarget enumeration.
from System import EnvironmentVariableTarget
# Create a temporary process environment variable.
SetEnvironmentVariable(‘MyVar’, ‘Hello’)
print ‘MyVar =’, GetEnvironmentVariable(‘MyVar’)
# Create a permanent user environment variable.
SetEnvironmentVariable(‘Var2’, ‘Goodbye’, EnvironmentVariableTarget.User)
print ‘Var2 =’, GetEnvironmentVariable(‘Var2’)
print ‘Var2 =’, GetEnvironmentVariable(‘Var2’, EnvironmentVariableTarget.User)
raw_input(‘\nOpen the Environment Variables dialog box...’)
# Delete the temporary and permanent variables.
print ‘\nDeleting the variables...’
SetEnvironmentVariable(‘MyVar’, None)
SetEnvironmentVariable(‘Var2’, None, EnvironmentVariableTarget.User)
print ‘MyVar =’, GetEnvironmentVariable(‘MyVar’)
print ‘Var2 =’, GetEnvironmentVariable(‘Var2’, EnvironmentVariableTarget.User)
# Pause after the debug session.
raw_input(‘\nPress any key to continue...’)
The example begins with the usual assembly imports. It then creates a new environment variable
using the
SetEnvironmentVariable()
method. If you call
SetEnvironmentVariable()
without
specifying a particular level, then the .NET Framework creates a temporary process environment
variable that only lasts for the current session.
The next step creates a permanent user environment variable. In this case, you must supply an
EnvironmentVariableTarget
enumeration value as the third argument. This portion of the example
also demonstrates something interesting. If you create a new permanent environment variable in
a process, the .NET Framework won’t update that process (or any other process for that matter).
Consequently, the first call to
GetEnvironmentVariable()
fails, as shown in Figure 10-14.
To see the environment variable, you must either restart the process or you must call
GetEnvironmentVariable()
with an
EnvironmentVariableTarget
enumeration value. As a result,
the second call succeeds. At this point, the example pauses so you can open the Environment Variables
dialog box and see for yourself that the environment variable actually does exist as a permanent value.
Deleting an environment variable is as simple as setting it to
None
using the
SetEnvironmentVariable()
method. However, you need to delete permanent environment variables
by including the
EnvironmentVariableTarget
enumeration value, or the .NET Framework won’t
delete it. Unlike the Python method, you won’t get an error when checking for environment variables
that don’t exist using the .NET method. Instead, you’ll get a value of
None
, as shown in Figure 10-14.
548592c10.indd 217
2/24/10 12:48:33 PM
www.finebook.ir
Do'stlaringiz bilan baham: |