如何使用shelve实现Python虚拟文件系统

eli*_*eac 5 python filesystems shelve

我已经设置了一个模拟操作系统的Python脚本.它有一个命令提示符和一个虚拟文件系统.我正在使用shelve模块来模拟文件系统,它是多维的,以支持目录层次结构.但是,我无法实现'cd'命令.我不知道如何进出目录,即使我在第一次启动程序时创建了一小组目录.这是我的代码:

import shelve

fs = shelve.open('filesystem.fs')
directory = 'root'
raw_dir = None
est_dir = None

def install(fs):
    fs['System'] = {}
    fs['Users'] = {}
    username = raw_input('What do you want your username to be? ')
    fs['Users'][username] = {}

try:
    test = fs['runbefore']
    del test
except:
    fs['runbefore'] = None
    install(fs)

def ls(args):
    print 'Contents of directory', directory + ':'
    if raw_dir:
        for i in fs[raw_dir[0]][raw_dir[1]][raw_dir[2]][raw_dir[3]]:
            print i
    else:
        for i in fs:
            print i

def cd(args):
    if len(args.split()) > 1:
        if args.split()[1] == '..':
            if raw_dir[3]:
                raw_dir[3] = 0
            elif raw_dir[2]:
                raw_dir[2] = 0
            elif raw_dir[1]:
                raw_dir[1] = 0
            else:
                print "cd : cannot go above root"

COMMANDS = {'ls' : ls}

while True:
    raw = raw_input('> ')
    cmd = raw.split()[0]
    if cmd in COMMANDS:
        COMMANDS[cmd](raw)

#Use break instead of exit, so you will get to this point.
raw_input('Press the Enter key to shutdown...')
Run Code Online (Sandbox Code Playgroud)

我没有收到错误,我只是不知道怎么做,也不知道除了'python搁置文件系统'之外还要搜索什么,这并没有得到任何有用的东西.

Dav*_*son 8

我提供了一些代码来帮助您,但首先,一些可以帮助您设计的整体建议:

  • 您更改目录时遇到困难的原因是您以错误的方式表示当前目录变量.您当前的目录应该类似于列表,从顶级目录到当前目录.一旦你有了这个,你只需根据他们的目录选择存储文件如何使用shelve(考虑到Shelve中的所有键必须是字符串).

  • 您似乎计划将文件系统表示为一系列嵌套字典 - 这是一个不错的选择.但请注意,如果更改了可变对象shelve,则必须a)将writeback设置为True,并且b)调用fs.sync()来设置它们.

  • 您应该在一个类而不是一系列函数中构建整个文件系统.它可以帮助您保持共享数据的有序性.以下代码不遵循这一点,但值得考虑.

所以,我修好了,cd并为你写了一个基本的mkdir命令.让它们工作的关键是,如上所述,current_dir是一个显示当前路径的列表,并且还有一个简单的方法(current_dictionary函数)从该列表到相应的文件系统目录.

有了它,这是让你入门的代码:

import shelve

fs = shelve.open('filesystem.fs', writeback=True)
current_dir = []

def install(fs):
    # create root and others
    username = raw_input('What do you want your username to be? ')

    fs[""] = {"System": {}, "Users": {username: {}}}

def current_dictionary():
    """Return a dictionary representing the files in the current directory"""
    d = fs[""]
    for key in current_dir:
        d = d[key]
    return d

def ls(args):
    print 'Contents of directory', "/" + "/".join(current_dir) + ':'
    for i in current_dictionary():
        print i

def cd(args):
    if len(args) != 1:
        print "Usage: cd <directory>"
        return

    if args[0] == "..":
        if len(current_dir) == 0:
            print "Cannot go above root"
        else:
            current_dir.pop()
    elif args[0] not in current_dictionary():
        print "Directory " + args[0] + " not found"
    else:
        current_dir.append(args[0])


def mkdir(args):
    if len(args) != 1:
        print "Usage: mkdir <directory>"
        return
    # create an empty directory there and sync back to shelve dictionary!
    d = current_dictionary()[args[0]] = {}
    fs.sync()

COMMANDS = {'ls' : ls, 'cd': cd, 'mkdir': mkdir}

install(fs)

while True:
    raw = raw_input('> ')
    cmd = raw.split()[0]
    if cmd in COMMANDS:
        COMMANDS[cmd](raw.split()[1:])

#Use break instead of exit, so you will get to this point.
raw_input('Press the Enter key to shutdown...')
Run Code Online (Sandbox Code Playgroud)

这是一个示范:

What do you want your username to be? David
> ls
Contents of directory /:
System
Users
> cd Users
> ls
Contents of directory /Users:
David
> cd David
> ls
Contents of directory /Users/David:
> cd ..
> ls
Contents of directory /Users:
David
> cd ..
> mkdir Other
> ls
Contents of directory /:
System
Users
Other
> cd Other
> ls
Contents of directory /Other:
> mkdir WithinOther
> ls
Contents of directory /Other:
WithinOther
Run Code Online (Sandbox Code Playgroud)

值得注意的是,到目前为止这只是一个玩具:还有很多工作要做.这里有一些例子:

  • 现在只有目录这样的东西 - 没有常规文件.

  • mkdir 不检查目录是否已存在,它将覆盖一个空目录.

  • 您不能ls将特定目录作为参数(例如ls Users),只能使用当前目录.

不过,这应该向您展示一个用于跟踪当前目录的设计示例.祝好运!