[Tutor] using command line arguments

Christian Tismer tismer@appliedbiometrics.com
Sat, 27 Mar 1999 16:06:52 +0100


Robert Burrows wrote:
> 
> Hello,
> 
> How can I use a command line argument in range()? I think I need something
> like C's atoi().

Right, a command line argument always comes as a string.
The sys.argv list is a list of string which you need to
parse.

The string module has exactly that function which you mention:
>>> import string
>>> s="123"
>>> string.atoi(s)
123
>>> 

Friends are string.atof for floats and string.atol for longs.
string.atoi provides you with an extra parameter 'base' which
defaults to 10, but here you can use 16 for instance if you
want atoi to parse hexadecimal numbers.

If you don't need an extra base parameter, it is easier to
just use the standard functions int and float, which don't
need to be imported.
>>> int("123")
123
>>> 

There is another issue if you are handling command line
parameters: Your program should recover gracefully
if the user did not specify a parameter at all, or if it was
no string. The easiest way to do this is to catch an exception.
Here the quick example:
>>> try:
... 	int("123c")
... except ValueError:
... 	print "this was not a number"
... 	raise SystemExit, 1
... 	
this was not a number
Traceback (innermost last):
  File "<interactive input>", line 5, in ?
SystemExit: 1
>>> 

Now, after we have figured out the details, we can write
a minimum comand line handler for your case.
The following sample program prints a number range to
your console, or dies with an error message.

#from here
def int_tuple_from_cmdline():
      """return exactly two integers form sys.argv
         or die with an error message
      """
      import sys
      args = sys.argv[1:] # drop first entry (progpath)
      if len(args) != 2:
          raise SystemExit("expected two integer parameters")
      for i in range(len(args)):
          try:
             args[i] = int(args[i])
          except ValueError:
             raise SystemExit("Parameter %d is no integer:%s" %(i+1,
args[i]))
      return tuple(args)

start, stop = int_tuple_from_cmdline()
print range(start, stop)
#to here

Now, here is my session log:

D:\tmp>python log.py 2 11
[2, 3, 4, 5, 6, 7, 8, 9, 10]

D:\tmp>python log.py 2
expected two integer parameters

D:\tmp>python log.py 2 notanumber
Parameter 2 is no integer:notanumber

hope this helps - ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer@appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101   :    *Starship* http://starship.python.net
10553 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home