如何使用Python获取固定父路径下名称不可预测的目录完整路径
方案说明
你当前采用的模拟终端按键+Tab补全的方案容错性极差,窗口焦点偏移、系统响应延迟、终端快捷键配置变动都会导致逻辑失效,完全不需要绕操作终端这层,直接通过文件系统遍历就能拿到目标路径,稳定性远高于GUI模拟方案。
已知固定父路径的规则为 /usr/local/insight/results/images/toolsDB/lauto_ptest_s{当日日期}/w1,且该路径下永远仅存在1个随机命名的目标子目录,直接遍历该父路径下的子目录即可拿到完整路径,不需要操作终端。
推荐实现(稳定无依赖)
import datetime from pathlib import Path import pyautogui def get_target_dir(): # 拼接已知固定父路径 current_date = datetime.datetime.now().strftime("%Y-%m-%d") parent_path = Path(f"/usr/local/insight/results/images/toolsDB/lauto_ptest_s{current_date}/w1") # 筛选父路径下的所有子目录 sub_dirs = [item for item in parent_path.iterdir() if item.is_dir()] if len(sub_dirs) != 1: raise RuntimeError(f"父路径下预期存在1个目标目录,实际检测到{len(sub_dirs)}个,请检查路径规则") return sub_dirs[0].resolve() def open_images_directory(): target_path = get_target_dir() # 唤起终端直接跳转 pyautogui.hotkey('ctrl', 'alt', 'shift', 'w') pyautogui.sleep(0.5) pyautogui.write(f"cd {target_path}\n") return str(target_path) if __name__ == "__main__": result_path = open_images_directory() print(f"获取到的目标完整路径:{result_path}")
兼容原有逻辑的实现(不推荐,稳定性差)
如果一定要沿用你当前模拟Tab补全的逻辑,需要通过终端快捷键把补全后的行内容剪切到剪贴板,再读取剪贴板解析路径,参考实现如下:
- 依赖:需要先安装
pyperclip库,且系统装有xclip(Debian/Ubuntu系可通过apt install xclip安装)
import pyautogui import datetime import pyperclip import time def open_images_directory(): pyautogui.hotkey('ctrl', 'alt', 'shift', 'w') time.sleep(0.5) current_date = str(datetime.datetime.now()).split()[0] pyautogui.write( f'cd /usr/local/insight/results/images/toolsDB/lauto_ptest_s{current_date}/w1/' ) pyautogui.sleep(0.5) # 触发Tab补全 pyautogui.hotkey('tab') pyautogui.sleep(0.2) # UNIX终端默认快捷键:Ctrl+U剪切光标位置到行首的所有内容,此时光标在行尾,会剪切整行cd命令 pyautogui.hotkey('ctrl', 'u') time.sleep(0.1) # 从剪贴板读取内容,解析路径 terminal_line = pyperclip.paste() full_path = terminal_line.removeprefix('cd ').strip() # 把剪切的命令粘贴回终端执行 pyperclip.copy(terminal_line) pyautogui.hotkey('ctrl', 'y') pyautogui.press('enter') return full_path
注意:该方案完全依赖GUI操作的时序和焦点,只要执行过程中弹出系统通知、切换窗口、系统卡顿,就会拿到错误结果,仅做参考,优先使用文件系统遍历的方案。
内容的提问来源于stack exchange,提问作者I'm not a robot
相关产品推荐
相关产品推荐

