我正在创建一个简单的shell程序,它接受用户对餐厅的命令。但是我很困惑如何接受来自用户的多个输入,以便shell可以读取它,然后将其解释为与调用的函数一起使用。在iinventory = {
"apple": 0,
"beets": 0,
"carrots": 0}
total=20
def handle_commands():
keep_going=True
while keep_going:
command=input("$ ").split()
var1=input()
var2=input()
if command == var1 + var2:
var1="loadrecipefile"
var2=recipe_file
loadrecipefile(recipe_file)
elif command == "printrecipes":
printrecipes()
elif command == "printiinventory":
printiinventory()
elif command == "printmoney":
printmoney()
elif command == "preparedish ":
command=input().split(" ")
preparedish(recipe_name)
elif command == "buyingredient ":
command=input().split(" ")
buyingredient(name, number)
elif command == "quit":
keep_going=False
break
else:
print("Sorry that is not an acceptable command")
return
def loadrecipefile (recipe_file):
infile=open(recipe_file)
Linelist=infile.readlines()
for line in Linelist:
wordList=line.split()
r1={'apple':int(wordList[1]),'beets':int(wordList[2]),'carrots':int(wordList[3])}
cookbook={wordList[0]:r1}
def printrecipes():
for name,ingred in cookbook.items():
print(name + " " + str(ingred['apple']) + " " + str(ingred['beets']) + " " + str(ingred['carrots']))
def buyingredient(name, number:int):
global total
total_spent=0
if number + total_spent > total:
print("Not enough cash!")
iinventory[name] += number
total -= number
def printiinventory():
print(iinventory['apple'],iinventory['beets'],iinventory['carrots'])
def printmoney():
print(total)
def CanPrepareDish(recipe_name):
recipe = cookbook[recipe_name]
for ingred in recipe:
if ingred not in iinventory:
return False
if iinventory[ingred] < recipe[ingred]:
return False
return True
def preparedish(recipe_name):
if not CanPrepareDish(recipe_name):
print("Not enough ingredients")
else:
recipe = cookbook[recipe_name]
for ingred in recipe:
iinventory[ingred] -= recipe[ingred]
if recipe_name in iinventory:
iinventory[recipe_name] +=1
else:
iinventory[recipe_name] = 1
print("Dish prepared")
handle_commands()
例如,如果用户要执行:
^{pr2}$
程序应该能够接受所有3个不同的输入,然后按空格分割输入,然后执行函数buy component。我不知道如何在一行命令中接受多个输入。在
而且,对于printrecipes()函数,我希望它打印在loadrecipefile函数中创建的烹饪书,但是它说没有定义烹饪书,所以我如何使用loadrecipefile函数中的食谱来处理printrecipes()。烹饪书是一本字典,我试着在函数之外设置cookbook={},但是printrecipes()只是将其打印为空白,而不是打印在loadrecipe文件中创建的食谱def loadrecipefile (recipe_file):
infile=open(recipe_file)
Linelist=infile.readlines()
for line in Linelist:
wordList=line.split()
r1={'apple':int(wordList[1]),'beets':int(wordList[2]),'carrots':int(wordList[3])}
cookbook={wordList[0]:r1}
print(cookbook)
例如,使用上面的代码,它将打印食谱:loadrecipefile("recipe_file.txt")
{'Recipe1': {'apple': 1, 'beets': 4, 'carrots': 3}}
{'Recipe2': {'apple': 0, 'beets': 2, 'carrots': 4}}
{'Recipe3': {'apple': 3, 'beets': 0, 'carrots': 1}}
{'Recipe4': {'apple': 2, 'beets': 1, 'carrots': 0}}
使用printrecipes()它应该打印出来Recipe1 1 4 3
Recipe2 0 2 4
Recipe3 3 0 1
Recipe4 2 1 0
任何帮助都将不胜感激。在