【超简单,不到一百行】操作系统课设-文件管理

效果:

用python实现了简单的指令:mkdir(创建目录)、ls(查看目录下所有文件)、cd(访问目录)、touch(创建文件)、rm (删除目录或者文件)

代码如下:

TYPE_DIR=0
TYPE_DOC=1

class MyFile:
    fileType:int
    fileName:str
    child:dict
    parent=None
    def __init__(self,name:str,parent,fileType:int) -> None:
        self.child=dict()
        self.parent=parent
        self.fileName=name
        self.fileType=fileType
        self.child[".."]=parent
    def __repr__(self) -> str:
        return self.fileName
    def __str__(self) -> str:
        return self.fileName
    def getPath(self)->str:
        pass
Home=MyFile("home",None,TYPE_DIR)
def analysis_args(args:list[str],workspace:MyFile):
    try:
        command=args[0]
        if(command=="cd"):
            if(len(args)!=2 ):
                raise Exception
            child:MyFile=workspace.child.get(args[1])
            if(child==None):
                print("No such file or directory")
                raise Exception
            elif(child.fileType!=TYPE_DIR):
                print("Not a directory")
                raise Exception
            else:
                return 0,child
        elif(command=="ls"):
            if(len(args)!=1):
                raise Exception
            for file in workspace.child:
                if(file!=".."):
                    print(file)
        elif(command=="mkdir"):
            workspace.child[args[1]]=MyFile(args[1],workspace,TYPE_DIR)
        elif(command=="rm"):
            child:MyFile=workspace.child.get(args[1])
            if(child!=None):
                workspace.child.pop(args[1])
            else:
                print("No such file or directory")
                raise Exception
        elif(command=="touch"):
            child:MyFile=workspace.child.get(args[1])
            if(child==None):
                workspace.child[args[1]]=MyFile(args[1],workspace,TYPE_DOC)
        elif(command=="exit"):
            if(len(args)!=1):
                raise Exception
            else:
                return 1,None
        else:
            raise Exception
    except:
        print("Illegal import!")

    return 0,None

if __name__ == "__main__":
    workspace:MyFile=Home
    path=""
    while(True):
        print("Myos@mamawhes:~/{}{}$".format(path,workspace),end=" ")
        input_str=input()
        #print(input_str)
        args=input_str.split(" ")
        flag,child=analysis_args(args,workspace)
        if(child!=None):
                if(args[1]==".." and args[0]=="cd"):
                    path=path[:len(path)-len(child.fileName)-1]
                else:
                    path+=workspace.fileName+"/"
                workspace=child        
        if(flag==1):
            break
        

猜你喜欢

转载自blog.csdn.net/qq_38830492/article/details/135286011