Python "while" 使用 "if" 语句循环

Python "while" loop with an "if" statement

我在 "while" 循环开始时遇到了一些 "if" 语句的问题。我的目标是检查是否已经将三个文件下载到工作站。如果是这样,脚本将开始下一个任务。否则,脚本将等待 300 秒,并在成功所需的时间内再次尝试下载文件。到目前为止,我有类似下面发布的代码,它似乎工作正常但结果最终是错误的。

if not os.path.exists(somefile_1) or not os.path.exists(somefile_2) or not os.path.exists(somefile_3):
        readyToSend = 0
        while (readyToSend == 0):
            if not os.path.exists(somefile_1) or not os.path.exists(somefile_2) or not os.path.exists(somefile_3):
                print 'There are some files missing. Restarting script.'
                lgr.info('There are some files missing. Restarting script.')
                start=300
                while start > 0:
                    time.sleep(1)
                    print 'Script will restart automatically in: ', start, '\r',
                    start -=1
                removePIDfile()
                execfile(r'D:\Workspace\tools\PKG_Maker\PKG_Maker.py')
            elif os.path.exists(somefile_1) and os.path.exists(somefile_2) and os.path.exists(somefile_3):
                readyToSend = 1
                print 'Restarting script not necessary. Files downloaded.'

我很确定使用相同的 "if" 语句两次是没有用的,但如果没有这个,循环就会启动计时器(内部的小循环)甚至不检查这些文件是否存在。

上面这部分代码没有按预期工作。我发现即使我可以在工作站上看到文件,我也会得到一些文件丢失的输出。搞砸了这些 "if" 和 "while" 陈述,现在(由于我的经验不足)我无法弄清楚......

我愿意学习,所以也许有人能告诉我应该怎么做,或者它的哪一部分毁了它。

当您可以用相同的方式处理三个文件时,您正在分别处理它们。我建议如下:

from os.path import exists

ready = 0
files = [somefile_1, somefile_2, somefile_3]

while not all(exists(f) for f in files):
    print 'There are some files missing. Restarting script.'
    sleep(300)
    removePIDfile()
    execfile(r'D:\Workspace\tools\PKG_Maker\PKG_Maker.py')

print 'Files downloaded'

这也去除了额外的 if 语句等。由于您没有提供 PKG_Maker.py 中的任何代码,我无法进一步帮助您,但由于它也是 python ,您可能可以直接从循环中调用它而不是使用 execfile.