202
❘
CHAPTER 10
Using ironPython for AdministrAtion tAsks
print ‘Good to see you’, arg.split(‘:’)[1]
# Say hello to the user.
elif arg in (‘-s’, ‘--Hello’) or arg.upper() in (‘/S’, ‘/HELLO’):
print ‘Hello!’
else:
raise ArgumentException(‘Invalid Argument’, arg)
except ArgumentException:
usage()
sys.exit(2)
# Pause after the debug session.
raw_input(‘\nPress any key to continue...’)
The .NET implementation is a little simpler than the Python implementation — at least if you want
to use both kinds of command line switches. This example begins by importing the required .NET
assemblies. The example also relies on
sys
to provide the
exit()
function.
The code begins by checking the number of arguments. When using .NET parsing, you
must have at least three command line arguments to receive any input. The example uses the
ArgumentException()
method to raise an exception should the user not provide any inputs.
In the IronPython example, the code uses a special technique to get rid of the script name.
The .NET method also gets rid of the application name and the script name. In this case, the
code creates a new array,
Arguments
, to hold the command line arguments. You must make
Arguments
large enough to hold all of the command line arguments, so the code uses the
Array
.CreateInstance()
method to create an
Array
object with two fewer elements than the origi-
nal array provided by
GetCommandLineArgs()
. The
Array.CreateInstance()
method requires
two inputs: the array data type and the array length. The
Array.Copy()
method moves just the
command line arguments to
Arguments
. The
Array.Copy()
method requires five inputs: source
array, source array starting element, destination array, destination array starting element, and
the number of elements to copy.
At this point, the code can begin parsing the input arguments. Notice that unlike the Python method,
you can parse all the permutations in a single line of code using the .NET method. The example pro-
vides the same processing as the Python method example, so that you can compare the two techniques.
As with the Python method, the .NET method raises an exception when the user doesn’t provide cor-
rect input. The result is that the example displays usage instructions for the application. Figure 10-4
shows the output from this example.
The Listing 10-4 code line
elif ‘-g‘ in arg or ‘--Greet‘ in arg or
‘/G‘ in arg.upper() or ‘/GREET‘ in arg.upper():
appears on one line
in the example application, even though it appears on multiple lines in this book
due to space considerations. Remember that IronPython lacks any form of line
continuation character. All your code must appear on a single line.
Do'stlaringiz bilan baham: