![](/img/trans.png)
[英]Write a program that accepts a positive integer from the user and prints the first four multiples of that integer. Use a while loop
[英]How to create a shell program that accepts commands and prints a “$” prompt to indicate that a user can input a command using a while loop?
我是Python的初學者,我不確定如何創建一個可以接受命令(例如,printrecipes,printinventory,load等)的簡單Shell程序。
輸入應如下所示:
$ loadrecipes
$ printmoney()
20
對於此shell,我嘗試使用while循環,以便即使他們輸入了可接受的命令,它也可以繼續執行程序而不會崩潰。
def handle_commands():
keep_going=True
command=input("$" + " ")
while keep_going:
if command == '$ quit':
keep_going = False
break
elif command == "$ loadrecipefile(recipe_file)"
j
elif command == "$ printrecipes":
printrecipes()
elif command == "$ printiinventory":
printiinventory()
elif command == "$ printmoney":
printmoney()
elif command == "$ buyingredient":
我不知道該怎么辦。 命令是loadrecipes(recipe_file)接受一個參數,所有打印命令都不接受參數,buyingredient(ingredient_name,number:int)接受2個參數(成分名稱和這些成分中的多少)。
因此,對於每個命令,我都創建了一個對應的函數。 例如對於printiinventory()我有:
def printiinventory():
print(iinventory['apple'],iinventory['beets'],iinventory['carrots'])
因此,如果命令是:
$ printiinventory
0 4 3
它應該出來像這樣
因此,您的流程應如下所示:
while True:
command = input("$ ")
if command is ...
elif ...:
與您所擁有的非常相似,所不同的是您不必期望$
在用戶輸入中。 輸入函數將輸出傳遞的參數,並僅返回用戶的輸入,而不返回同一行中的其余內容。 因此,您應該檢查命令,例如command == "printrecipes"
等。
說明:
這段代碼:
x = input(str)
等效於:
print(str); x = input(str)
唯一的不同是print()創建了新行,因此輸入將取自打印內容正下方的行。
您可以使用IO低級Python模塊來模擬這種行為(即在同一行中進行打印),但是沒有必要這樣做。
為了解析命令,您可以選擇經典的命令行界面語法,該語法使用空格分隔命令名稱和參數,或者可以創建自己的解析器。 萬一您第一次使用,可以使用Python的內置argparse
模塊。 如果您想使用第二個(這更讓人頭疼,尤其是對於初學者而言),則必須從頭開始編寫自己的解析器。 如果您知道regex沒什么大不了的,但是恐怕您應該在網站上問另一個問題。 我建議您看一些教程。 只是谷歌搜索:“使用我自己的命令解析器python”可以為您提供成千上萬個結果,即使其中大多數將用於經典的命令行解析語法。
我注意到您使用某種標志來檢查是否需要繼續進行循環。 這在您使用的代碼段中沒有用; 只需使用break
命令,您就可以使用了。
通過仔細查看OP的注釋,我看到您正在嘗試編寫要由Python腳本執行的Python代碼。 您可以肯定地做到這一點; 您已經有了eval
和exec
模塊,但請注意,這是一個非常危險的做法,很容易將代碼注入到您的程序中,從而造成巨大的安全漏洞。 強烈建議您不要這樣做。 您必須將命令解析與任務執行分開。 用戶永遠無法直接訪問程序的控制流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.