Python 打印另一个文件的内容,并在输入错误时循环原始输入
我正在做一个应用程序,必须为它做一个简短的屏幕手册。为了不让脚本中再出现100行“打印这个,打印那个”,我把它写在了一个单独的文件中。但是,我不知道如何打印另一个文件的内容 我还遇到了此循环的问题:Python 打印另一个文件的内容,并在输入错误时循环原始输入,python,Python,我正在做一个应用程序,必须为它做一个简短的屏幕手册。为了不让脚本中再出现100行“打印这个,打印那个”,我把它写在了一个单独的文件中。但是,我不知道如何打印另一个文件的内容 我还遇到了此循环的问题: if option == 'help': print "content of the help file" elif option == 'start': run(host='localhost', port=8080) else: print "not a valid op
if option == 'help':
print "content of the help file"
elif option == 'start':
run(host='localhost', port=8080)
else:
print "not a valid option, try again"
在循环结束时,如果用户输入了一个无效选项,我如何使其可以重试而不必再次执行该文件
假设您的帮助内容位于名为
help.txt的文件中:
validInputs = set(["help", "start"])
userInput = raw_input("What would you like to do? ").strip()
while userInput not in validInputs:
print "That was an incorrect input. Try again"
userInput = raw_input("What would you like to do? ").strip()
if userInput == 'help': # print contents of help file
with open('help.txt') as infile:
for line in infile:
print line.rstrip()
elif userInput == 'start':
run(host='localhost', port=8080)
在您的while条件下,或
应该是和
;即使选项
是'start'
,条件也会传递给选项!='“帮助”
,while将重新执行@inspectorG4dget谢谢!我犯了一个愚蠢的错误。
validInputs = set(["help", "start"])
userInput = raw_input("What would you like to do? ").strip()
while userInput not in validInputs:
print "That was an incorrect input. Try again"
userInput = raw_input("What would you like to do? ").strip()
if userInput == 'help': # print contents of help file
with open('help.txt') as infile:
for line in infile:
print line.rstrip()
elif userInput == 'start':
run(host='localhost', port=8080)