mycmd Demo

来源:互联网 发布:gitlab windows 编辑:程序博客网 时间:2024/05/21 15:42

import osimport shutilimport timecurrPath=os.path.dirname(os.path.abspath(__file__))#动态获取当前路径n=currPathdef help(cmd=None):    if cmd is None or len(cmd)==0:        with open(n+'\help.zz',encoding="utf-8")as f:            for line in f :                print(line,end="")    else:        with open(n+"/"+cmd[0]+".zz", encoding="utf-8")as f:            for line in f:                print(line,end="")    print()def dir(cmd=None):    if cmd is None or len(cmd)==0:            for line in os.listdir(currPath) :                if os.path.isdir(line):                    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),"\t <dir>",line)                else:                    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), "\t      ", line)    else:            for line in os.listdir(cmd[0]):                if os.path.isdir(line):                    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), "\t <dir>", line)                else:                    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), "\t       ", line)def del1(cmd=None):    if os.path.isfile(cmd[0]) == True:        os.remove(cmd[0])def rd(cmd=None):    if not os.listdir(cmd[0]):        if os.path.isdir(cmd[0]):            shutil.rmtree(cmd[0])    else:        print("非空目录不可删")def cp(cmd=None):    if cmd[0] == "-r":       shutil.copytree(cmd[1],cmd[2])    else:        shutil.copyfile(cmd[0],cmd[1])def mv(cmd=None):       shutil.move(cmd[0],cmd[1])def cd(cmd=None):    if cmd is not None and len(cmd) > 0:            global currPath            os.chdir(cmd[0])  # 改变当前工作目录            currPath = os.getcwd()#返回当前目录的Unicode对象cmd_dict={"help":help,"dir":dir,"cd":cd,"del1":del1,"rd":rd,"cp":cp,"mv":mv}if __name__ == "__main__":#主线程运行,确保是独立运行测试    while True:        key = input(currPath+">")        if key == "exit":            break        keyAndPrarms=key.split(' ')#以空格拆分输入的字符串        help=cmd_dict[keyAndPrarms[0]]#通过k得到V,V为help()方法        help(cmd=keyAndPrarms[1:])#如果输入help cd a则只会截取到cdprint("程序结束!")
原创粉丝点击