5

I am very newbie in Python but I have to implement for school a command line interpreter in Python language, but I am kinda lost in how to do that.

I have already read some tutorials and created a simple file called functions.py where i include some simple functions like this:

def delete(loc):
    if os.path.exists(loc) == True:
        os.remove(loc)
        print "Removed"
    else:
        print "File not exists"

Now.. here is the thing.. in order to use this I must import it inside the python command interpreter, like...

import functions
functions.delete("file to delete")

How can I make a Shell/CLI so instead of have to write all of this I can just write like:

delete file_name

Thanks!

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
PGZ
  • 485
  • 1
  • 5
  • 11
  • I think my definition of "CLI" differs somewhat. You want to write an interpreter for a small "programming language" (DSL), right? – AndiDog Jan 23 '11 at 08:30

3 Answers3

9

Or if you want a cmd shell, you could use the cmd lib. It offers python interfaces to making command lines. http://docs.python.org/library/cmd.html

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
4

I think you should now to use simple argparse module to get command line arguments


import argparse

from functions import delete

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file')

args = parser.parse_args()

delete(args.file)

Hope this should work for you

Sultan

sultan
  • 5,978
  • 14
  • 59
  • 103
1

You might want to check my personal REPL for some inspiration. I wrote it during a tutorial series. Actual source may be found here. It probably does a few things you won't need... Still it could be a good read. :)

Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105