我的等待文件出现在目录中的Python脚本会在验证此存在级别上进行过多的迭代

如何解决我的等待文件出现在目录中的Python脚本会在验证此存在级别上进行过多的迭代

我创建了一个Python脚本,该脚本需要在目录中存在一个文件。例如,从浏览器(例如,使用Selenium)下载此文件。我想象的工作流程如下:

  1. 想象一个可能会在所需目录中创建文件的操作(例如,在Windows / Linux的默认下载目录中使用Selenium下载)
  2. 最多执行10次,请尝试执行此操作并等待10秒
  3. 在这10秒钟之后,每次都要检查目录中是否存在该文件:如果是,请中断循环并继续执行脚本,因为现在有了所需的文件。如果不是,则继续循环直到完成10次(或更少)。
  4. 完成10次并且目录中仍不存在该文件时,引发致命错误

我的问题

即使文件存在于目录中,循环也会执行10次而不是中断。

脚本(最小和可执行示例)

来源

    file_was_downloaded = False
    for u in range(10):
        click(Link('download the file in the directory'))
        time.sleep(10)
        files = os.listdir('C:/Users/XYZ/Downloads/')
        for f in files:
            if f.startswith("the_file.jpg") and not f.endswith(".crdownload"):  # ".crdownload" if a suffix appended to the name of the file by Google Chromium/Chrome if it's not completely downloaded
                file_was_downloaded = True
                break
    if not file_was_downloaded:
       print(datetime.datetime.now() + " - The file may not be present in the directory.\n")
       exit(-1)
    
    # Below this line,we can use the file.

测试

您可以删除行click,并通过在脚本运行时将所需文件添加到目录中来自行替换。您将看到,即使文件在目录中,循环也将继续迭代。这就是问题所在,我不知道为什么会这样。

预期行为

在目录中检测到文件“存在”时,循环中断。

实际行为

循环继续迭代。

解决方法

您的break语句仅中断“ for f in files”循环。 如果在“ for u range”循环中添加另一个:

if file_was_downloaded:
   break
  
,

尝试这样的事情:

int findProcessID(wchar_t processName[]);

int main()
{
    // Declare a wchar_t array to put process name.
    wchar_t processName[100];

    // Input the process name,such as "notepad.exe".
    printf("Enter process name: ");
    scanf_s("%ls",processName);

    // Get the PID.
    int pid = findProcessID(processName);
    if (pid > 0) {
        printf("The process \"%ls\" is found.\n\tAnd PID is %d\n",processName,pid);
    }
    else {
        printf("Not found the process \"%ls\".\n",processName);
    }


    system("PAUSE");

    return 0;
}

int findProcessID(wchar_t processName[]) {
    // Enumerate all processes.
    PROCESSENTRY32 entry;

    // dwSize: The size of the structure,in bytes. 
    // Before calling the Process32First function,// set this member to sizeof(PROCESSENTRY32). 
    // If you do not initialize dwSize,Process32First fails.
    entry.dwSize = sizeof(PROCESSENTRY32);

    // Includes all processes in the system in the snapshot.
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,NULL);

    if (Process32First(snapshot,&entry) == TRUE) {
        while (Process32Next(snapshot,&entry) == TRUE) {
            if (wcscmp(entry.szExeFile,processName) == 0) {
                // Match the process name.
                return entry.th32ProcessID;
            }
        }
    }
    return -1;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-