簡體   English   中英

執行一個函數以在循環上返回值,直到該函數返回False-Python

[英]Execute a function to return a value on a loop until that function returns 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

我需要完成上面的while循環,還需要訪問返回的文件名。 我該怎么做呢? 上面的代碼顯然不起作用,但是它概述了我想要實現的目標。

在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。
因此,如果函數失敗,則在while中斷時循環,但如果找到文件名則繼續

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM