文件系统模拟程序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
发布评论