Mats has mentioned the modules getopt and argparse etc. These are
primarily aimed at option parsing ("-v", "-o foo"). Your situation
occurs _after_ the option parsing (in your case, there are no options).
Alan has talked about explicitly checking the length of sys.argv, much
as you are doing, or accessing the (missing) argument and catching an
exception.
There's a middle ground, which is a little more flexible, which is to
_consume_ the command line arguments. The argv array is a list, and can
be modified. So:
def main(argv):
cmd = argv.pop(0) # collect the command word
badopts = False
# mandatory first argument
if not argv:
print("%s: missing first argument" % cmd, file=sys.stderr)
badopts = True
else:
first = argv.pop(0)
# optional second argument
if argv:
second = argv.pop(0) # explicit argument 2, use it
else:
second = None # or some otherdefault
if argv:
print("%s: extra arguments: %r" % (cmd, argv), file=sys.stderr)
badopts = true
if badopts:
print("%s: invalid invocation, aborting" % cmd, file=sys.stderr)
return 2
... work with first and second ...
You can see here that we process the arguments from left to right,
consuming the valid ones as we find them, and setting a flag for
incorrect arguments. At the end we test the flag and abort if it is set.
otherwise we process knowing we have valid values.
One important aspect of the above code is that you do not wire in an
explicit length for sys.argv such as 2 or 3. That way you can easily
change your code later if you want more arguments without running around
adjusting such fixed numbers.
The other important aspect is usability: the above code complains about
each issue it encounters, and finally quits with an additional message.
In a real programme that addition message would include a "usage"
message which describes the expected arguments.
Cheers,
Cameron Simpson <c...@cskk.id.au>
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor