Python“while”循环带有“if”语句

2024-04-27 08:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我在“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”语句两次是没有用的,但是没有这个,loop启动计时器(内部有一个小循环),甚至没有检查这些文件是否存在。在

以上代码的这一部分没有按预期工作。我发现,即使我可以看到工作站上的文件,我也得到一些文件丢失的输出。搞砸了这些“如果”和“while”的陈述,而现在(由于我经验不足),我就是搞不懂。。。在

我愿意学习,所以也许有人能告诉我应该怎么做,或者是哪一部分正在破坏这一切。在


Tags: or文件pathifosexistsscriptnot
1条回答
网友
1楼 · 发布于 2024-04-27 08:09:50

当你可以用同样的方法处理三个文件时,你要分别处理三个文件。我建议如下:

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。在

相关问题 更多 >