The Environment Class

From IronPython Cookbook

This entry illustrates using the System.Environment class, which provides "information about, and means to manipulate, the current environment and platform".

This class has many members that provide information about the environment. For details of all of them, see the Environment Members page.

Some of the properties include:

from System import Environment

# Command line for the current process (unparsed)
print Environment.CommandLine

# The current directory
print Environment.CurrentDirectory

# Set or get the exit code
Environment.ExitCode = 1

# CLR Version
version = Environment.Version
print version.Major, version.Minor

# Gets the user name of the person who started the current thread.
print Environment.UserName

# Gets the fully qualified path of the system directory.
print Environment.SystemDirectory

And so on...

There are also various methods, many for working with environment variables. Through os.environ (using the standard library os module), which is a case insensitive dictionary like object, you can get and set environment variables for the current process.

What you can't do, is set system wide environment variables. You can however do this with the Environment.SetEnvironmentVariable method - specifically the overload that takes two strings and an EnvironmentVariableTarget value.

from System import Environment, EnvironmentVariableTarget

# Set a system wide environment variable
Environment.SetEnvironmentVariable('variable', 'value', EnvironmentVariableTarget.Machine)

# Set an environment variable for the local user
Environment.SetEnvironmentVariable('variable', 'value', EnvironmentVariableTarget.User)

If value is empty (None or an empty string) and the environment variable named by variable exists, the environment variable is deleted.

If the target parameter is User or Machine, the environment variable is not automatically copied to the current process. If target is User, the environment variable is copied to the current process when the user who stored the variable starts a new process. If target is Machine, the environment variable is copied to the current process when any user on the local machine starts a new process.

Back to Contents.