Wednesday, September 19, 2012

Some More Python

As I work through the exercises from Core Python Programming 2e I'll post my solutions to some of the exercises that I find interesting.

Here's a wrapper for the Windows command-line interface that allows one to use the Unix/Linux ls, more, cat, cp, mv and rm commands to manipulate files in Windows:

import os
import string

class shell(object):
    def cmd(self):
        while 1:
            cmdLine = raw_input("$ ")
            if "ls" in cmdLine and len(cmdLine) == 2:
                os.system("dir")
            if "ls" in cmdLine[:cmdLine.find(" ")]:
                path = cmdLine[cmdLine.find(" "):]
                os.system("dir" + path)
            if "more" in cmdLine[:cmdLine.find(" ")]:
                path = cmdLine[cmdLine.find(" "):]
                os.system("more" + path)
            if "cat" in cmdLine[:cmdLine.find(" ")]:
                path = cmdLine[cmdLine.find(" "):]
                os.system("type" + path)
            if "cp" in cmdLine[:cmdLine.find(" ")]:
                path1 = cmdLine[cmdLine.find(" "):cmdLine.rfind(" ")]
                path2 = cmdLine[cmdLine.rfind(" "):]
                os.system("copy" + path1 + path2)
            if "mv" in cmdLine[:cmdLine.find(" ")]:
                path1 = cmdLine[cmdLine.find(" "):cmdLine.rfind(" ")]
                path2 = cmdLine[cmdLine.rfind(" "):]
                os.system("ren" + path1 + path2)
            if "rm" in cmdLine[:cmdLine.find(" ")]:
                path = cmdLine[cmdLine.find(" "):]
                os.system("del" + path)