执行函数以返回循环中的值,直到该函数返回false -python



我具有将文件从一台服务器移动到另一台服务器的函数。执行时该功能将返回文件名,或者如果没有传输文件,则返回false。

我想在循环中调用此功能,直到它返回false。每次调用函数时,我还需要访问返回的值(文件名)。我可以做一个或另一个,但我遇到了两者遇到的困难。这是我想在伪代码中完成的工作:

移动文件的函数(这不会更改):

def move_first_matching_file():
    try:
        # find the first file that matches a wildcard file name
        # move the file from remote server to local server
        # delete file from remote server
        return name_of_file
    except:
        return False

在其他模块中调用上述功能(这需要工作):

while move_first_matching_file() as name_of_file is not False:
    # process name_of_file

我需要完成上面的WALE循环,但还需要访问返回的文件名。我该怎么做呢?我上面的代码显然不起作用,但概述了我想实现的目标。

您不能在Python中做类似的事情,因为分配始终是一个陈述。通常的模式是:

while True:
    name_of_file = move_first_matching_file()
    if not name_of_file:
        break
    ...

如在评论中所述,您也可以做

filename = move_first_matching_file()
while filename:
    # process file
    # call the function again and reassing the filename
    filename = move_first_matching_file()

因为您的功能如果成功(总是代表true),则发送字符串,如果不成功,则为false。
因此,如果函数失败,则在断路时循环,但是如果找到文件名,请继续

最新更新