CPythonist

CLI.py: Source Code

import getpass, os, shutil, datetime, time, sys, subprocess;

def splitWord(word):
    return [char for char in word];

print("""CLI
Made by ... 

First enter the single-word command,
and then give the required information
for the command.

Type 'help' for help menu.
""");

name = getpass.getuser();
path = "C:\\Users\\" + name;

while True:
    print(path + "> ", end="")
    try:
        com = input().lower()
        assert com.isspace() != True and com != ''
        commands = ('copy', 'mkdir', 'shutdown',
                    'date', 'echo', 'exit',
                    'help', 'rmdir', 'time',
                    'cli', 'cd', 'start')
        given = com.split()
        if given == []:
            print("\nEmpty command not accepted.\n")
        else:
            for i in given:
                if i in commands:
                    comH = i
                    break
            else:
                print("\nInvalid command.\n")
                continue
            if comH == commands[0]:
                try:
                    source = input("\nEnter source file/directory (full path)> ")
                    try:
                        assert source.isspace() != True and source != ""
                        if os.path.isfile(source):	
                            dest = input("\nEnter destination folder (full path)> ")
                            try:
                                assert os.path.isdir(dest) and dest != "" and dest.isspace() != True
                                shutil.copy(source, dest)
                                print("\nFile copied successfully.\n")
                            except AssertionError:
                                print("\nDirectory not found.\n")
                            except PermissionError:
                                print("\nAccess denied.\n")
                            except FileExistsError:
                                print("\nThe file already exists.\n")
                        elif os.path.isdir(source):
                            dest = input("\nEnter destination folder (full path)> ")
                            try:
                                assert os.path.isdir(dest) and dest != "" and dest.isspace() != True
                                if '/' in source:
                                    names = source.split("/")
                                elif '//' in source:
                                    names = source.split("//")
                                elif '\\' in source:
                                    names = source.split("\\")
                                elif '\\\\' in source:
                                    names = source.split("\\\\")
                                else:
                                    print("\nEither illegal seperation character given or\ninvalid seperation \
character.\nUse '/', '//', '\' or '\\'.\n")
                                    continue
                                try:
                                    os.mkdir(str(dest) + "\\" + str(names[-1]))
                                    dest = str(dest) +  "\\" + str(names[-1])
                                    shutil.copytree(source, dest, dirs_exist_ok=True)
                                    print("\nFolder copied successfully.\n")
                                except FileExistsError:
                                    ok = input(f"\nA directory with the name {names[-1]} already exists in \
{dest}. Overwrite ([y]es / [n]o)> ").lower()
                                    if 'y' in ok:
                                        dest = str(dest) +  "\\" + str(names[-1])
                                        shutil.copytree(source, dest, dirs_exist_ok=True)
                                        print("\nFolder copied successfully.\n")
                                    else:
                                        print("\nDirectory not copied.\n")
                            except AssertionError:
                                print("\nDirectory not found.\n")
                            except PermissionError:
                                print("\nAccess denied.\n")
                            except FileExistsError:
                                print("\nThe folder already exists.\n")
                        else:
                            print("\nFile or directory not found.\n")
                    except AssertionError:
                        print("\nEmpty file path or folder path.\n")
                except AssertionError:
                    print("\nFile not found.\n")
                except PermissionError:
                    print("\nAccess denied.\n")
            elif comH == commands[1]:
                finalDir = input("\nDirectory path (without directory name)> ")
                if os.path.isdir(finalDir):
                    dirName = input("\nEnter the directory name> ")
                    illegal = ['<', '>', ':', '"', '/', '\\', '|', '?', '*']
                    explodedName = splitWord(dirName)
                    for i in explodedName:
                        if i in illegal:
                            print("\nIllegal character for directory name.\n")
                            break
                    else:
                        try:
                            os.mkdir(str(finalDir) + "\\" + str(dirName), mode=0o666)
                            assert (os.path.isdir(str(finalDir) + "\\" + str(dirName)))
                            print("\nDirectory created.\n")
                        except FileExistsError:
                            print("\nDirectory already exists.\n")
                        except AssertionError:
                            print("\nUnable to create directory.\n")
                        except PermissionError:
                            print("\nInsufficient permissions to create directory.\n")
                else:
                    print("\nDirectory not found.\n")
            elif comH == commands[2]:
                print("\nShutting down...")
                os.system("shutdown /hybrid /s /t 000")
            elif comH == commands[3]:
                dateToday = datetime.date.today().strftime("%d %B %Y, %A")
                print("\nDate and day today is: " + str(dateToday) + "\n")
            elif comH == commands[4]:
                print("\n" + com.removeprefix("echo ") + "\n")
            elif comH == commands[5]:
                sys.exit(0)
            elif comH == commands[6]:
                print("""
COPY      Copys file/folder from a source to target folder
MKDIR     Creates a directory in the target location
SHUTDOWN  Shuts down the computer
DATE      Displays the date today
ECHO      Displays the characters after the command
EXIT      Exits CLI
HELP      Displays this help page
RMDIR     Removes a directory from the target location
TIME      Displays the time now
CLI       Displays copyright
CD        Changes the directory
START     Starts an installed app, or file/folder specified
""")
            elif comH == commands[7]:
                finalDir = input("\nDirectory path> ")
                try:
                    assert os.path.isdir(finalDir)
                    shutil.rmtree(finalDir)
                    print("\nDirectory removed.\n")
                except AssertionError:
                    print("\nDirectory not found.\n")
                except PermissionError:
                    print("\nInsufficient permissions available for action.\n")
            elif comH == commands[8]:
                print("\nPress Ctrl + C to interrupt.\n")
                try:
                    while True:
                        timeNow = datetime.datetime.now().strftime("%I : %M : %S  %f")
                        print("Time now is: " + str(timeNow), end='\r')
                        time.sleep(0.000001)
                except KeyboardInterrupt:
                    print("\n")
            elif comH == commands[9]:
                print("""
CLI by a devotee of Python.
(c) Thiruvalluvan Kamaraj.
Made for Windows 10 or later.
""")
            elif comH == commands[10]:
                pathTrail = input("\nEnter entire path> ")
                print()
                if os.path.isdir(pathTrail) == True:
                    path = pathTrail
                    del pathTrail
                else:
                    print("\nDirectory not found.\n")
            elif comH == commands[11]:
                opened = False
                filename = input("\nEnter app name, or file/directory that you want to open.")
                if os.path.isfile(filename):
                    os.startfile(filename)
                    opened = True
                elif os.path.isdir(filename):
                    dirPath = "r'explorer /select," + filename + "'";
                    subprocess.Popen(dirPath)
                    opened = True
                else:
                    if not filename.endswith(".exe"):
                        filename = filename + ".exe"
                    search = r"C:\Program Files"
                    for root, dirs, files in os.walk(search):
                        for name in files:
                            if name == filename:
                                os.startfile(name)
                                opened = True
                            break
                        break
                    else:
                        search = r"C:\Program Files (x86)"
                        for root, dirs, files in os.walk(search):
                            for name in files:
                                if name == filename:
                                    os.startfile(name)
                                    opened = True
                                break
                            break
                        else:
                            search = r"C:\Windows"
                            for root, dirs, files in os.walk(search):
                                for name in files:
                                    if name == filename:
                                        os.startfile(name)
                                        opened = True
                                    break
                                break
                if opened == False:
                    print(f"\nNo installed app with name '{filename}', or, no such file or directory.\n")
                else:
                    print("\n")
    except EOFError:
        print("\nInvalid command.\n")
    except AssertionError:
        print("\nEmpty command not accepted.\n")
    except KeyboardInterrupt:
        print("\nKeyboard Interrupt.\n")