Sheleveを使用してPython仮想ファイルシステムを実装する方法
-
26-10-2019 - |
質問
OSをシミュレートするPythonスクリプトを設定しました。コマンドプロンプトと仮想ファイルシステムがあります。ディレクトリの階層をサポートするために、Sheleveモジュールを使用してファイルシステムをシミュレートしています。ただし、「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...')
エラーが発生していません。どうすればいいのかわからず、「Python Shelve File System」以外に何を検索すべきかわからないだけで、有用なものはありません。
解決
以下に役立つコードを提供しますが、まず、デザインに役立つ全体的なアドバイスをお楽しみいただけます。
ディレクトリの変更に苦労している理由は、現在のディレクトリ変数を間違った方法で表現しているためです。現在のディレクトリは、トップレベルのディレクトリから現在のディレクトリまで、リストのようなものでなければなりません。それを手に入れると、ディレクトリに基づいてSheleveを使用してストアファイルを使用する方法について選択するだけです(Shelveのすべてのキーが文字列でなければならないことを考慮してください)。
ファイルシステムを一連のネストされた辞書として表現することを計画しているようです。良い選択です。ただし、可変オブジェクトを変更した場合に注意してください
shelve
, 、a)書き込みをtrueに設定し、b)fs.sync()を呼び出して設定する必要があります。一連の機能ではなく、クラスでファイルシステム全体を構築する必要があります。共有データを編成するのに役立ちます。以下のコードはそれに従いませんが、考える価値があります。
だから、私は修正しました cd
また、あなたのために初歩的なMKDIRコマンドを書きました。それらを機能させるための重要なことは、上で言ったように、current_dirをあなたの現在のパスを示すリストにすること、そして簡単な方法を持つことです( current_dictionary
関数)そのリストから適切なFilesystem Directoryに取得します。
それで、ここにあなたが始めるためのコードがあります:
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...')
そして、これがデモンストレーションです:
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
引数として特定のディレクトリがある(ls Users
)、現在のディレクトリのみ。
それでも、これは現在のディレクトリを追跡するためのデザインの例を示すはずです。幸運を!