如何多次接受用户输入,然后在完成后执行脚本的其余部分?

How to accept user input multiple times and then execute the rest of the script when they're done?

我想编写一个脚本,用户可以在其中获取目录中所有文件的列表,然后输入完整的文件名来查看它们。现在,我的脚本将让用户执行一次,然后继续执行脚本的下一部分。我希望它留在这部分,让他们能够继续输入文件名并浏览尽可能多的文件。然后,我希望它说出类似 "Press Enter to continue..." 的内容,然后它将继续到脚本的下一部分。我认为这将是某种循环,但我是 Python 的新手。我希望一切都有意义。

这是我目前所拥有的。

for root, dirs., files in os.walk("/home/user/Documents"):
    for file in files:
        print(os.path.join(root, file))
fname = raw_input('Enter filename to view:')
f = open(fname, 'r')
print f.read()

所以我希望用户每次都输入另一个文件名时重复,当用户选择这样做时,他们可以继续我脚本的下一部分。现在它在继续之前只经过一次。在此先感谢您的帮助!

顺便说一句,现在输入的方式永远不会发生。

您需要为您的用户提供 "escape" 选项,否则他会随心所欲地提交文件。 (您可以尝试一个转义条件,例如:如果用户键入 0 ,您将继续打印下一部分 "Press Enter to continue..")

所以伪编码有点像:

initialize a list
store directory files in list
while input != escape character
  ask user for file name
  if file name inside list:
    print file
    print "Press Enter to Continue"
  else:
    print error
    print "Press Enter to Continue"

希望这能给你一个大概的想法。

因为, a while statement可能是这个程序流程的最佳匹配。可能是这样的:

import os

def does_user_want_to_continue():
    # implement this, so it returns True or False,
    # depending on what your user wants.
    # Probably involves asking the user and accepting their input.

should_continue = True
while should_continue:
    for root, dirs, files in os.walk("/home/user/Documents"):
        for file in files:
            print(os.path.join(root, file))
    fname = raw_input('Enter filename to view:')
    f = open(fname, 'r')
    print f.read()
    should_continue = does_user_want_to_continue()

您也可以从循环内部跳出循环,而不是通过更改其条件表达式的计算结果:

import os

while True:
    for root, dirs, files in os.walk("/home/user/Documents"):
        for file in files:
            print(os.path.join(root, file))
    fname = raw_input('Enter filename to view '
                      '(leave empty to proceed without viewing another file):')

    if not fname:  # Empty strings are 'falsy'.
        break

    # The rest of the while clause will only be executed
    # if above we didn't break out of the loop. If we did
    # break out, the script continues with the code after
    # this loop.
    f = open(fname, 'r')
    print f.read()

这与 das-g 的回答基本相同,但它实际上询问您是否要继续的选项,我相当确定这应该适合您的需要:

def yorn():
while True:
    answer=raw_input('yes or no: ')
    if answer == 'no':
        more_script()
        break
    else:
        for root, dirs., files in os.walk("/home/user/Documents"):
            for file in files:
                print(os.path.join(root, file))
        fname = raw_input('Enter filename to view:')
        f = open(fname, 'r')
        print f.read()
def more_script():
print "were you would add the next portion"
yorn()