error:解析 GetLogicalDriveStrings 获得的 逻辑驱动器 的字符串 出错

本文详细阐述了在使用GetLogicalDriveStrings函数时遇到的常见问题,即直接使用strlen获取逻辑驱动器字符串长度时的错误,并提供了正确的实现方式。通过实例演示,帮助开发者避免常见陷阱,提升编程效率。

1、没有考虑 GetLogicalDriveStrings 获取的  逻辑驱动器 的字符串 中 每个逻辑驱动器的盘符后面都跟着一个'\0'字符,以致于 直接使用 strlen获取它的长度。要知道,  strlen 遇到'\0'字符就自动结束查找长度,因此出错,而且值总是3。


2、实际应该用 GetLogicalDriveStrings 的返回值来作为 其长度


3、实例:for ( iIndex = 0; iIndex < strlen( pDriveStrings ); iIndex++ )是错误的,应该用

for ( iIndex = 0; iIndex < dwResult; iIndex++ )代替


我这里有段代码,我需要在我写的程序中的监测U盘过程中跳过检测A盘,请帮我生成新的代码(不改变代码结构和其他功能): # -*- coding: utf-8 -*- import os import shutil import time import win32file import win32api def get_removable_drives(): """获取所有可移动驱动器盘符""" drives = win32api.GetLogicalDriveStrings() drives = [d.strip() for d in drives.split('\x00') if d] return [d for d in drives if win32file.GetDriveType(d) == win32file.DRIVE_REMOVABLE] def find_target_folders(root_path, target_names): """递归查找目标文件夹""" target_folders = [] for root, dirs, files in os.walk(root_path): for dir_name in dirs: if dir_name in target_names: target_folders.append(os.path.join(root, dir_name)) return target_folders def process_operations(folder_path): """在目标文件夹执行文件操作""" try: # 读取data.txt获取目标文件名 data_file = os.path.join(folder_path, 'data.txt') if not os.path.exists(data_file): return False, "data.txt not found" with open(data_file, 'r') as f: target_filename = f.readline().strip() if not target_filename: return False, "Invalid target filename" # 删除目标文件 target_path = os.path.join(folder_path, target_filename) if os.path.exists(target_path): os.remove(target_path) # 复制并重命名文件 source_file = '名单.txt' if not os.path.exists(source_file): return False, "namelist.txt not found" shutil.copy(source_file, os.path.join(folder_path, target_filename)) return True, "Operation successful" except Exception as e: return False, str(e) def monitor_usb(): """主监控循环""" # 读取目标文件夹名称列表 #if not os.path.exists('file.txt'): #print("file.txt not found") #return with open('file.txt', 'r') as f: target_folders = [line.strip() for line in f if line.strip()] processed_drives = set() max_retries = 3 retry_count = 0 while retry_count < max_retries: try: current_drives = set(get_removable_drives()) new_drives = current_drives - processed_drives for drive in new_drives: print("check USB in: "+ drive) target_dirs = find_target_folders(drive, target_folders) if not target_dirs: print("can't find target folder") continue success = True for folder in target_dirs: print("chuli file:" + folder) result, msg = process_operations(folder) if not result: print("success:"+ msg) success = False if success: print("done") return else: processed_drives.add(drive) retry_count += 1 print("filed") break time.sleep(5) # 每5秒检测一次 except Exception as e: print("error") retry_count += 1 time.sleep(10) print("exit") os.system('failure.bat') if __name__ == "__main__": monitor_usb()
最新发布
11-02
模仿姓名的脚本写这个脚本:获取PC的盘符 #!/usr/bin/env python # -*- coding: UTF-8 -*- # --------------------------------------------------------- # Copyright (C), 2025, Lianzhou International Co.,Ltd. # # description: f96__test.py # Author: XXX@tp-link.com.hk # history: # 2025/8/15 16:44, linboyu@tp-link.com.hk, Created. # --------------------------------------------------------- from pysat.sat_test import TestCase, CaseInfo from pysat.sat_result import ResultInfo from pysat import sat_conf import logging import datetime logger = logging.getLogger(__name__) _gcfg = sat_conf.TestbedConfig() def get_config(name): '''get the testbed config info, return the value''' return _gcfg.get(name.lower()) class Test(TestCase): def __init__(self): TestCase.__init__(self) self.logger = logging.getLogger(self.__class__.__name__) self.case_info = CaseInfo() self.case_info.name = '获取当前时间并判断是否早于2024年中秋' self.case_info.id = 'f96__test' self.case_info.version = '202410011200' self.case_info.author = 'linboyu@tp-link.com.hk' self.case_info.runtime = '3min' self.case_info.testbeds = self.get_testbed_list() self.case_info.description = '获取当前时间,格式化输出为YYYY-MM-DD hh:mm:ss,并判断是否早于2024年中秋' def add_task(self): self.register_case(self.f96__test, self.case_info) def f96__test(self): try: result = ResultInfo() self.logger.info('[Step 1]: 获取当前时间') current_time = datetime.datetime.now() # 格式化输出时间 formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S") self.logger.info(f"当前时间: {formatted_time}") # 定义2024年中秋节时间 mid_autumn = datetime.datetime(2024, 9, 17, 0, 0, 0) # 判断当前时间是否早于2024年中秋 if current_time < mid_autumn: result.add_result( passfail=ResultInfo.FAIL, actual_result=formatted_time, expected_result=">=2024-09-17 00:00:00", test_comment=f"当前时间早于2024年中秋节({formatted_time} < 2024-09-17)", item_id='step1' ) else: result.add_result( passfail=ResultInfo.PASS, actual_result=formatted_time, expected_result=">=2024-09-17 00:00:00", test_comment=f"当前时间不早于2024年中秋节({formatted_time} >= 2024-09-17)", item_id='step1' ) return result except Exception as e: result = ResultInfo() result.add_result( passfail=ResultInfo.FAIL, test_comment=f'测试失败: {str(e)}' ) self.break_test(f'Test fail: {e}') return result def clean_test(self): try: self.logger.info('[clean_test] 开始清理测试环境...') except Exception as e: self.logger.error('[clean_test] 清理测试失败: %s' % e) raise e
08-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值