212
❘
CHAPTER 10
Using ironPython for AdministrAtion tAsks
appear in the
Variables
list, so you must obtain them using
os.environ[Var]
. Figure 10-11 shows
typical output from this example.
FIgURE 10-11:
The environment variables are displayed in alphabetical order.
Setting the Environment Variables Using Python
Python makes it relatively easy to set environment variables. However, the environment variables
you create using IronPython affect only the current command prompt session and the current user.
Consequently, if you start another application in the current session (see the section “Starting Other
Command Line Applications” later in the chapter for details), it can see the environment variable,
but if you start an application in a different session or start a graphical application, the environment
variable isn’t defined. In addition, changes you make to existing environment variables affect only
548592c10.indd 212
2/24/10 12:48:32 PM
www.finebook.ir
Interacting with the Environment
❘
213
the current session. Nothing is permanent. Listing 10-7 shows how to modify environment variables
using the Python method.
LISTINg 10-7:
Setting an environment variable using the Python method
# Import the required Python modules.
import os
# Create a new environment variable.
os.environ.__setitem__(‘MyVar’, ‘Hello’)
# Display its value on screen.
print ‘MyVar =’, os.environ[‘MyVar’]
# Change the environment variable and show the results.
os.environ.__setitem__(‘MyVar’, ‘Goodbye’)
print ‘MyVar =’, os.environ[‘MyVar’]
# Delete the variable, and then try to show it.
try:
os.environ.__delitem__(‘MyVar’)
print ‘MyVar =’, os.environ[‘MyVar’]
except KeyError as (KeyName):
print ‘Can\‘t display’, KeyName
# Pause after the debug session.
raw_input(‘\nPress any key to continue...’)
Setting and changing an environment variable use the same method,
os.environ.__setitem__()
.
In both cases, you supply a name/value pair (
MyVar
/
Hello
). When you want to see the value of the
environment variable, you request the value by supplying the name, such as
os.environ[‘MyVar‘]
for this example.
Deleting an environment variable requires use of
os.environ.__delitem__()
. In this case, you
supply only the name of the environment variable you want to remove.
If you try to display an environment variable that doesn’t exist, the interpreter raises a
KeyError
exception. The example shows the result of trying to print
MyVar
after you remove it using
os.environ.__delitem__()
. Figure 10-12 shows the output from this example.
FIgURE 10-12:
IronPython makes it easy to set, modify, and delete environment variables for the
current session.
548592c10.indd 213
2/24/10 12:48:32 PM
www.finebook.ir
Do'stlaringiz bilan baham: |