如何解决我的等待文件出现在目录中的Python脚本会在验证此存在级别上进行过多的迭代
我创建了一个Python脚本,该脚本需要在目录中存在一个文件。例如,从浏览器(例如,使用Selenium)下载此文件。我想象的工作流程如下:
- 想象一个可能会在所需目录中创建文件的操作(例如,在Windows / Linux的默认下载目录中使用Selenium下载)
- 最多执行10次,请尝试执行此操作并等待10秒
- 在这10秒钟之后,每次都要检查目录中是否存在该文件:如果是,请中断循环并继续执行脚本,因为现在有了所需的文件。如果不是,则继续循环直到完成10次(或更少)。
- 完成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 举报,一经查实,本站将立刻删除。