簡體   English   中英

如何使用 python 獲取不可預測的目錄路徑?

[英]how to get unpredictable directory path with python?

首先,我將簡要描述我要解決的問題:

我有一個基於 UNIX 的系統,它運行導致圖像創建的自動運行。

這些圖像保存在運行期間創建的目錄中,並且目錄的名稱是不可預測的[名稱取決於很多因素,而不是恆定的。]

該目錄是在恆定路徑下創建的,即:

/usr/local/insight/results/images/toolsDB/lauto_ptest_s + str(datetime.datetime.now()).split()[0] + /w1

所以,現在我得到了一個恆定形式的路徑,它是我完整路徑的一部分。 我試圖以一種愚蠢的方式獲得完整的路徑:

我編寫了一個腳本,通過按 ctrl+alt+sft+w 打開一個新終端,在終端中將 cd 命令寫入常量路徑,然后按 Tab 以完成完整路徑 [在常量路徑中總是有一個創建的目錄,因此按選項卡將始終讓我獲得完整路徑]。

從理論上講,我在終端中有一個完整路徑,我怎樣才能復制這個完整路徑並讓函數返回它?

這是我的代碼:


import pyautogui
import datetime


def open_images_directory():

    pyautogui.hotkey('ctrl', 'alt', 'shift', 'w')
    pyautogui.write(
        'cd' + ' /usr/local/insight/results/images/toolsDB/lauto_ptest_s' + str(datetime.datetime.now()).split()[
            0] + '/w1/')
    pyautogui.sleep(0.5)
    pyautogui.hotkey('tab') # now I have a full path in terminal which I want to return by func


open_images_directory()

不確定您如何使用pyautogui ,但正確的解決方案是使用一些glob 模式搜索目錄結構

例子:

from pathlib import Path

const_path = Path("const_path")
for path in [p for p in const_path.rglob("*")]:
    if path.is_dir():
        print(f"found directory {path}")
    else:
        print(f"found your image {path}")

const_path.rglob("*")遞歸搜索每個路徑(因此它將包含每個子目錄),最后一個將是您要搜索的路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM