[Tutor] A command line

Kirby Urner urnerk@qwest.net
Sat, 06 Oct 2001 12:42:45 -0700


At 08:51 PM 10/5/2001 +0200, Tor Stormwall wrote:
>Hi!
>
>I'm trying make a little interpreter that will other run
>commands.
>
>But why cant I do like this:


The sys.argv stuff is for capturing arguments passed
to Python from the operating system shell, not from
the Python shell.

If you're already in Python, then you just want to pass
your argument to commands directly, like this:

   >>> def commands(commline):
          if commline == "open":
              print "opening"
              return 1
          elif commline == "exit":
              return 0
          else:
              print "not a valid command"
              return 1

   >>> def interpreter(prompt='=> '):
          while 1:
              command = raw_input(prompt)
              if command:
                 rval = commands(command)
                 if not rval:
                      break
          else:  break


   >>> interpreter()
   => open
   opening
   => close
   not a valid command
   => duh
   not a valid command
   => exit
   >>>
   >>> interpreter()  # no at all command is another way to quit
   =>
   >>>

If you want to launch such a shell from the operating system,
you could stick the above in a module and do so, again without
arguments.  You could uses the sys.exit(0) thing to terminate
Python when done.  Again you don't need the argv stuff because
it's Python's own raw_input that's reading what the user types
in response to =>, not something entered at the DOS or UNIX
prompt for which something(s) you'd need to interrogate the
system.

Note:  there's are modules which do a lot of the work for you,
if you're wanting to build a shell.  shlex and cmd are the
two to look at.  'Python 2.1 Bible' (Hungry Minds, 2001) has
a whole chapter entitled 'Building Simple Command Interpreters'.
This is one of my favorite Python books by the way -- very
comprehensive and well-presented IMO.

Kirby