文件系统模拟程序python

编程入门 行业动态 更新时间:2024-10-07 04:31:03

<a href=https://www.elefans.com/category/jswz/34/1771295.html style=文件系统模拟程序python"/>

文件系统模拟程序python

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

>您更改目录时遇到困难的原因是您以错误的方式表示当前目录变量.您当前的目录应该类似于列表,从顶级目录到当前目录.一旦你有了这个,你只需根据他们的目录选择存储文件如何使用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 "

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 "

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...')

这是一个示范:

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

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

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

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

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

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

更多推荐

文件系统模拟程序python

本文发布于:2024-02-14 04:17:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1761660.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件系统   程序   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!