Current drive and directory

Jeff Epler jepler at unpythonic.net
Wed May 26 18:51:32 EDT 2004


You'll have to parse the command yourself.  If it's an "internal
command" (as cd must be), then execute it in Python, not via os.system().  

> print """MS-DOS Prompt
> 'Q' to Quit"""
> 
> import os
> command = ""
> 
> while command.lower() != "q":
>         directory = os.getcwd()
>         print "\n", directory, "\b>",
>         command = raw_input("\b")
          first, rest = command.split(None, 1)
          if first.lower() == "cd":
            os.chdir(rest)
          else
>           os.system(command)
... but you have to do other stuff like interpretation of quoting (For
example
    cd "C:\Program Files\"
), and os.chdir("c:\\Program Files\\") behaves differently than typing
"cd "C:\Program Files\" in command.com/cmd.exe (because the latter doesn't
change the current drive letter, it just changes the current directory
associated with the given drive letter)

Other things that must be done in Python, not by system():
    * "set" for environment variables
    * "a:" "b:" etc to change 
    * @echo off
    * flow control (IF ERRORLEVEL, GOTO, etc)
Some things are traditionally implemented in the shell, but may
not work if passed to system():
    * redirection
    * pipelines    
    * any advanced feature in a unix shell, like job control
If you want to do a shell right, there's a lot of work involved.

Jeff




More information about the Python-list mailing list